如何在向量中存储实现相同特征的不同类型,并在其上调用通用函数? [英] How do I store different types that implement the same trait in a vector and call common functions on them?

查看:90
本文介绍了如何在向量中存储实现相同特征的不同类型,并在其上调用通用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Rust,并且在实现多态方面遇到困难.我想使用数组存储CircleTest.

I'm learning Rust and I'm having difficulties in implementing polymorphism. I want to use an array to store either Circle or Test.

trait Poli {
    fn area(&self) -> f64;
}

struct Circle {
    x:      f64,
    y:      f64,
    radius: f64,
}

impl Circle {
    fn new (xx: f64, yy: f64, r: f64) -> Circle{
        Circle{ x: xx, y: yy, radius: r }
    }
}

impl Poli for Circle {
   fn area(&self) -> f64 {
       std::f64::consts::PI * (self.radius * self.radius)
   }
}

struct Test {
    x:      f64,
    y:      f64,
    radius: f64,
    test:   f64,
}

impl Test {
    fn new (xx: f64, yy: f64, r: f64, t: f64) -> Circle{
        Test{ x: xx, y: yy, radius: r, test: t, }
    }
}

impl Poli for Test {
    fn area(&self) -> f64 {
        std::f64::consts::PI * (self.radius * self.radius)
    }
}

我不知道如何制作一个向量来存储具有相同trait的类型:

I do not know how to make a vector to store types with the same trait:

let cir  = Circle::new(10f64, 10f64, 10f64);
let test = Test::new(10f64, 10f64, 10f64, 10f64);

//let mut vec: Vec<Poli> = Vec::new();   <---

我想从特征中迭代vector和call函数.有什么方法可以做到这一点,或者有其他选择吗?

I'd like to iterate the vector and call functions from the trait. Is there any way to do this, or some alternative?

我阅读了特征对象文档,但我认为这不是什么我想要.

I read the trait object documentation but I think it's not what I want.

推荐答案

链接到的页面,您需要将Poli实现结构存储为Vec<&Poli>Vec<Box<Poli>>,具体取决于您是要拥有值还是要存储引用:

As mentioned in the page you linked to, you'll need to either store the Poli implementing structs as Vec<&Poli> or Vec<Box<Poli>> depending on whether you want to own the values or just store a reference:

// Owned
let circle = Circle::new(10f64, 10f64, 10f64);
let test = Test::new(10f64, 10f64, 10f64, 10f64);

let polis = vec![Box::new(circle) as Box<Poli>, Box::new(test) as Box<Poli>];

for poli in polis {
    println!("{}", poli.area());
}

// Reference
let circle = Circle::new(10f64, 10f64, 10f64);
let test = Test::new(10f64, 10f64, 10f64, 10f64);

let polis = vec![&circle as &Poli, &test as &Poli];

for poli in polis {
    println!("{}", poli.area());
}

输出

314.1592653589793
314.1592653589793
314.1592653589793
314.1592653589793

演示

这篇关于如何在向量中存储实现相同特征的不同类型,并在其上调用通用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆