Vector of objects implementing a common trait in Rust: how to create and use?
Hi! I'm new to Rust and trying to understand polymorphism. I have a trait `Shape` with a method `area()`, and several structs (`Circle`, `Rectangle`) that implement it. I want to create a vector that can store objects of different types implementing this trait.
In C++ or Java I would write something like `vector shapes;` or `List shapes = new ArrayList<>();`. But in Rust I can't just write `Vec` — the compiler says the size of the trait is not known at compile time.
Here's my code that doesn't work:
```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:
```
No answers yet.
Log in to leave an answer
Blogs
Working with the File System in C#: A Complete Guide for Developers