Skip to content

Instantly share code, notes, and snippets.

@jac18281828
Created September 10, 2024 00:23
Show Gist options
  • Save jac18281828/724b3e09450cb8045d9d6f768fa7d2de to your computer and use it in GitHub Desktop.
Save jac18281828/724b3e09450cb8045d9d6f768fa7d2de to your computer and use it in GitHub Desktop.
Rust trait plaything
use core::panic;
trait Animal {
fn name(&self) -> &'static str;
fn talk(&self) {
println!("{} cannot talk", self.name());
}
}
struct Dog;
impl Dog {
fn new() -> Dog {
Dog
}
}
impl Animal for Dog {
fn name(&self) -> &'static str {
"Dog"
}
fn talk(&self) {
println!("{} says: Woof!", self.name());
}
}
struct Cat;
impl Cat {
fn new() -> Cat {
Cat
}
}
impl Animal for Cat {
fn name(&self) -> &'static str {
"Cat"
}
fn talk(&self) {
println!("{} says: Meow!", self.name());
}
}
fn parse_animal(animals: &String) -> Vec<Box<dyn Animal>> {
let mut result = Vec::new();
for animal in animals.split(",") {
match animal {
"dog" => result.push(Box::new(Dog::new()) as Box<dyn Animal>),
"cat" => result.push(Box::new(Cat::new()) as Box<dyn Animal>),
_ => panic!("unknown animal: {}", animal),
}
}
result
}
fn main() {
let animals = "dog,cat,dog,dog,cat".to_string();
parse_animal(&animals).iter().for_each(|animal| {
animal.talk();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment