Created
September 10, 2024 00:23
-
-
Save jac18281828/724b3e09450cb8045d9d6f768fa7d2de to your computer and use it in GitHub Desktop.
Rust trait plaything
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
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