Skip to content

Instantly share code, notes, and snippets.

@jultabary
Created January 15, 2022 14:20
Show Gist options
  • Save jultabary/cd5d528c3da59a7eb2b420765cf10690 to your computer and use it in GitHub Desktop.
Save jultabary/cd5d528c3da59a7eb2b420765cf10690 to your computer and use it in GitHub Desktop.
POO in rust
use std::any::Any;
trait Animal {
fn give_my_name(&self) -> String;
fn eat(&self) {
println!("miam !!!!");
}
fn as_any(&self) -> &dyn Any;
}
// Domain
struct Dog {
}
impl Dog {
fn bite(&self) {
println!("ça fait mal !!!!");
}
}
impl Animal for Dog {
fn give_my_name(&self) -> String {
String::from("Chien")
}
fn as_any(&self) -> &dyn Any {
self
}
}
struct Cat { }
impl Animal for Cat {
fn give_my_name(&self) -> String {
String::from("Cat")
}
fn as_any(&self) -> &dyn Any {
self
}
}
fn main() {
let dog = Dog { };
let cat = Cat { };
/*let mut animals = Vec::new() as Vec<Box<dyn Animal>>;
animals.push(Box::new(dog));
animals.push(Box::new(cat));*/
let mut animals = Vec::new() as Vec<&dyn Animal>;
animals.push(&dog);
animals.push(&cat);
if let Some(chien) = animals.get(0) {
let dog_2 = chien.as_any().downcast_ref::<Dog>().unwrap();
dog_2.bite();
} else {
panic!("Pourquoi y en a pas");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment