Created
August 24, 2018 09:37
-
-
Save rust-play/eb67027040b1cba1a3d3ac7ce7423273 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains hidden or 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 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