Skip to content

Instantly share code, notes, and snippets.

@mykhailokrainik
Forked from rust-play/playground.rs
Last active September 13, 2018 07:46
Show Gist options
  • Save mykhailokrainik/fe5be4c221ddfb6cc9b5fc367af0a9ca to your computer and use it in GitHub Desktop.
Save mykhailokrainik/fe5be4c221ddfb6cc9b5fc367af0a9ca to your computer and use it in GitHub Desktop.
Rust shared structs.
trait Fruit {
fn who_am_i(&self) -> String;
}
struct Apple {
name: String,
}
struct Banana {
name: String,
color: String,
}
impl Fruit for Apple {
fn who_am_i(&self) -> String {
format!("I am '{}'", self.name)
}
}
impl Fruit for Banana {
fn who_am_i(&self) -> String {
format!("I am '{} {}'", self.color , self.name)
}
}
fn apple() -> impl Fruit {
Apple {
name: "Apple".to_string(),
}
}
fn banana() -> impl Fruit {
Banana {
name: "Banana".to_string(),
color: "green".to_string(),
}
}
fn foods() -> Vec< Box<Fruit> > {
vec![Box::new(apple()), Box::new(banana()), Box::new(banana())]
}
fn main() {
println!("{}", apple().who_am_i());
println!("{}", banana().who_am_i());
println!("foods: ");
for fruit in foods().into_iter() {
println!("{}", fruit.who_am_i() )
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment