Skip to content

Instantly share code, notes, and snippets.

@tforgione
Created April 5, 2018 08:12
Show Gist options
  • Save tforgione/6c4b383ed9ac8accce3dbbba198ace1f to your computer and use it in GitHub Desktop.
Save tforgione/6c4b383ed9ac8accce3dbbba198ace1f to your computer and use it in GitHub Desktop.
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