Avatar ·

实现共同trait的对象向量在Rust中:如何创建和使用?

你好!我是Rust新手,正在尝试理解多态。我有一个`Shape` trait,包含`area()`方法,以及几个实现了该trait的结构体(`Circle`、`Rectangle`)。我想创建一个可以存储不同实现该trait的对象的向量。 在C++或Java中,我会写类似`vector shapes;`或`List shapes = new ArrayList<>();`的代码。但在Rust中,我不能直接写`Vec`——编译器提示trait的大小在编译时未知。 以下是我的无效代码: ```rust trait Shape { fn area(&self) -> f64; } struct Circle { radius: f64, } impl Shape for Circle { fn area(&self) -> f64 { std::f64::consts::PI * self.radius * self.radius } } struct Rectangle { width: f64, height: f64, } impl Shape for Rectangle { fn area(&self) -> f64 { self.width * self.height } } fn main() { let shapes: Vec = vec![ Circle { ra