Avatar ·

Comment obtenir une référence à un type concret à partir d'un trait-objet en Rust ?

Bonjour à tous ! Je suis débutant en Rust et j'ai rencontré un problème en travaillant avec des trait-objets. J'ai un trait `Animal` et deux structures qui l'implémentent : `Dog` et `Cat`. Je les stocke dans un vecteur en tant que `Box`, mais ensuite j'ai besoin d'accéder aux champs spécifiques à chaque type. Voici un code simplifié : ```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::new(Cat { name: "Whiskers".into(), lives_left: 9 }), ]; for animal in animals { animal.speak(); // Cela fonctionne // Mais comment obtenir breed pour Dog ou lives_left pour Cat ? } } ```