Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created August 24, 2018 09:37
Show Gist options
  • Save rust-play/eb67027040b1cba1a3d3ac7ce7423273 to your computer and use it in GitHub Desktop.
Save rust-play/eb67027040b1cba1a3d3ac7ce7423273 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
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