How to get a reference to a specific type from a trait object in Rust?
Hello everyone! I'm new to Rust and encountered a problem when working with trait objects. I have a trait `Animal` and two structs that implement it: `Dog` and `Cat`. I store them in a vector as `Box`, but later I need to access fields specific to each type.
Here's a simplified code:
```rust
trait Animal {
fn speak(&self);
}
struct Dog {
name: String,
breed: String,
}
struct Cat {
name: String,
lives_left: u8,
}
impl Animal for Dog {
fn speak(&self) {
println!("Woof!");
}
}
impl Animal for Cat {
fn speak(&self) {
println!("Meow!");
}
}
fn main() {
let animals: Vec> = vec![
Box::new(Dog { name: "Rex".into(), breed: "Labrador".into() }),
Box::ne