Created
March 10, 2025 17:29
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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