Skip to content

Instantly share code, notes, and snippets.

@DrLarck
Created March 10, 2025 17:29
Show Gist options
  • Save DrLarck/54353b078ae6eddb146a1f886818d5ce to your computer and use it in GitHub Desktop.
Save DrLarck/54353b078ae6eddb146a1f886818d5ce to your computer and use it in GitHub Desktop.
Implémentation d'un système d'héritage simple, en utilisant le Dynamic Dispatch
/// Trait pet
/// Utilisable comme une "interface" ici
trait Pet {
fn sound(&self);
}
/// Struct Dog qui implémente le trait (interface) "Pet"
struct Dog;
impl Dog {
fn new() -> Dog {
Dog {}
}
}
/// Implémentation de "l'interface" "Pet"
impl Pet for Dog {
fn sound(&self) {
println!("🐕 Woof");
}
}
/// Struct Cat qui implémente le trait (interface) "Pet"
struct Cat;
impl Cat {
fn new() -> Cat {
Cat {}
}
}
/// Implémentation de "l'interface" "Pet"
impl Pet for Cat {
fn sound(&self) {
println!("🐈 Meow");
}
}
fn main() {
// On créer un vecteur qui peut contenir des éléments de type différents
// Pour les regrouper, il faut dire au compilateur que tous ces types
// héritent du Trait "Pet"
let pets: Vec<Box<dyn Pet>> = vec![Box::new(Dog::new()), Box::new(Cat::new())];
for pet in pets {
pet.sound();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment