mirror of
https://github.com/ahgamut/rust-ape-example.git
synced 2024-05-14 17:42:41 +00:00
46 lines
868 B
Rust
46 lines
868 B
Rust
// ./src/trait/dyn.md
|
|
|
|
|
|
struct Sheep {}
|
|
struct Cow {}
|
|
|
|
trait Animal {
|
|
// Instance method signature
|
|
fn noise(&self) -> &'static str;
|
|
}
|
|
|
|
// Implement the `Animal` trait for `Sheep`.
|
|
impl Animal for Sheep {
|
|
fn noise(&self) -> &'static str {
|
|
"baaaaah!"
|
|
}
|
|
}
|
|
|
|
// Implement the `Animal` trait for `Cow`.
|
|
impl Animal for Cow {
|
|
fn noise(&self) -> &'static str {
|
|
"moooooo!"
|
|
}
|
|
}
|
|
|
|
// Returns some struct that implements Animal, but we don't know which one at compile time.
|
|
fn random_animal(random_number: f64) -> Box<dyn Animal> {
|
|
if random_number < 0.5 {
|
|
Box::new(Sheep {})
|
|
} else {
|
|
Box::new(Cow {})
|
|
}
|
|
}
|
|
|
|
fn part0() {
|
|
let random_number = 0.234;
|
|
let animal = random_animal(random_number);
|
|
println!("You've randomly chosen an animal, and it says {}", animal.noise());
|
|
}
|
|
|
|
|
|
pub fn main() {
|
|
part0();
|
|
}
|
|
|