如何在向量中存储实现相同特征的不同类型并在其上调用常用函数?

时间:2016-04-01 13:46:37

标签: polymorphism rust traits

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

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来存储类型的向量:

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

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

我想迭代向量并从特征中调用函​​数。有没有办法做到这一点,或者有其他选择?

我读过the trait object documentation,但我认为这不是我想要的。

2 个答案:

答案 0 :(得分:5)

正如page you linked to中所述,您需要将Poli实施结构存储为Vec<&Poli>Vec<Box<Poli>>,具体取决于您是否要拥有这些值或只需存储参考:

// 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

Demo

答案 1 :(得分:0)

Dogbert's response之后,我玩了一下,发现这种方式适合我。我是Rust的新手,我不知道这是否显而易见,但我会留在这里帮助别人。

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

let mut vec: Vec<&Poli> = Vec::<&Poli>::new();
    vec.push(&circle);
    vec.push(&test);

for v in vec {
    println!("new {}", v.area());
}

Demo