Created
April 5, 2018 08:12
-
-
Save tforgione/6c4b383ed9ac8accce3dbbba198ace1f to your computer and use it in GitHub Desktop.
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
trait Animal { | |
fn speak(&self); | |
} | |
struct Dog; | |
impl Animal for Dog { | |
fn speak(&self) { | |
println!("Woof"); | |
} | |
} | |
impl Dog { | |
pub fn new() -> Dog { | |
Dog { | |
} | |
} | |
} | |
struct Cat; | |
impl Cat { | |
pub fn new() -> Cat { | |
Cat { | |
} | |
} | |
} | |
impl Animal for Cat { | |
fn speak(&self) { | |
println!("Meow"); | |
} | |
} | |
struct Zoo { | |
pub animals: Vec<Box<Animal>>, | |
} | |
impl Zoo { | |
pub fn new() -> Zoo { | |
Zoo { | |
animals: vec![], | |
} | |
} | |
pub fn add_cat(&mut self) { | |
self.animals.push(Box::new(Cat::new())); | |
} | |
pub fn add_dog(&mut self) { | |
self.animals.push(Box::new(Dog::new())); | |
} | |
} | |
fn main() { | |
let mut zoo = Zoo::new(); | |
zoo.add_cat(); | |
zoo.add_cat(); | |
zoo.add_dog(); | |
zoo.add_cat(); | |
zoo.add_dog(); | |
for animal in zoo.animals { | |
animal.speak(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment