Created
July 22, 2021 02:14
-
-
Save AXDOOMER/6beacde927d32bc1a76c04ad4692b9f4 to your computer and use it in GitHub Desktop.
Polymorphism with function calls in Rust
This file contains 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
struct Chat; | |
struct Chien; | |
trait Bruiteur { | |
fn bruit(&self) -> &str; | |
} | |
impl Bruiteur for Chat { | |
fn bruit(&self) -> &str { | |
"Nyan" | |
} | |
} | |
impl Bruiteur for Chien { | |
fn bruit(&self) -> &str { | |
"Woof" | |
} | |
} | |
fn main() { | |
let animaux : Vec<Box<dyn Bruiteur>> = vec![Box::new(Chat), Box::new(Chien)]; | |
for x in animaux { | |
println!("{}", x.bruit()); | |
} | |
} |
This file contains 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
enum Animal { | |
Chat(String), | |
Chien(String, i32) | |
} | |
fn describe(x: Animal) -> String { | |
match x { | |
Animal::Chat(name) => format!("{} is a cat", name), | |
Animal::Chien(name, weight) => format!("{} is a dog and weights {} pounds", name, weight), | |
} | |
} | |
fn main() { | |
let mut v: Vec<Animal> = Vec::new(); | |
v.push(Animal::Chat(String::from("Oreo"))); | |
v.push(Animal::Chien(String::from("Spot"), 20)); | |
for x in v { | |
println!("{}", describe(x)); | |
} | |
} |
This file contains 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
struct Chat; | |
struct Chien; | |
trait Bruiteur { | |
fn bruit(&self) -> &str; | |
} | |
impl Bruiteur for Chat { | |
fn bruit(&self) -> &str { | |
"Nyan" | |
} | |
} | |
impl Bruiteur for Chien { | |
fn bruit(&self) -> &str { | |
"Woof" | |
} | |
} | |
fn main() { | |
let mut v: Vec<&mut Bruiteur> = Vec::new(); | |
let mut chat = Chat; | |
let mut chien = Chien; | |
v.push(&mut chat); | |
v.push(&mut chien); | |
for x in v { | |
println!("{}", x.bruit()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment