Skip to content

Instantly share code, notes, and snippets.

@islishude
Last active September 15, 2019 08:18
Show Gist options
  • Save islishude/574218e8e839f775b51b374070dd6add to your computer and use it in GitHub Desktop.
Save islishude/574218e8e839f775b51b374070dd6add to your computer and use it in GitHub Desktop.
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