Skip to content

Instantly share code, notes, and snippets.

@AXDOOMER
Created July 22, 2021 02:14
Show Gist options
  • Save AXDOOMER/6beacde927d32bc1a76c04ad4692b9f4 to your computer and use it in GitHub Desktop.
Save AXDOOMER/6beacde927d32bc1a76c04ad4692b9f4 to your computer and use it in GitHub Desktop.
Polymorphism with function calls in Rust
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());
}
}
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));
}
}
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