Last active
September 15, 2019 08:18
-
-
Save islishude/574218e8e839f775b51b374070dd6add to your computer and use it in GitHub Desktop.
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
pub trait Bird { | |
fn fly(&self); | |
} | |
pub struct Duck; | |
pub struct Swan; | |
impl Bird for Duck { | |
fn fly(&self) { | |
println!("duck fly"); | |
} | |
} | |
impl Bird for Swan { | |
fn fly(&self) { | |
println!("swan fly"); | |
} | |
} | |
pub fn get_trait_0(switch: bool) -> Box<dyn Bird> { | |
if switch { | |
Box::new(Swan) | |
} else { | |
Box::new(Duck) | |
} | |
} | |
pub fn get_trait_1() -> impl Bird { | |
let s = Swan; | |
s | |
} | |
pub fn pass_bird_0(b: impl Bird) { | |
b.fly(); | |
} | |
pub fn pass_bird_1(b: &dyn Bird) { | |
b.fly(); | |
} | |
pub fn pass_bird_2<T>(b: T) -> () | |
where | |
T: Bird, | |
{ | |
b.fly(); | |
} | |
fn main() { | |
Box::new(Duck); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment