Created
May 4, 2024 17:30
-
-
Save ryanhossain9797/8b5d110032b8f216324cf9f6b7ea3e92 to your computer and use it in GitHub Desktop.
This file contains 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
struct GenericAnimal { | |
age: usize | |
} | |
impl GenericAnimal { | |
fn sleep(&self) { | |
println!("zzz"); | |
} | |
} | |
struct Tiger { | |
generic_features: GenericAnimal | |
} | |
impl Tiger { | |
fn roar (&self) { | |
println!("growl"); | |
} | |
} | |
struct Duck { | |
generic_features: GenericAnimal, | |
color: &'static str | |
} | |
impl Duck { | |
fn fly (&self) { | |
println!("flap flap flap"); | |
} | |
} | |
enum Animal { | |
Generic(GenericAnimal), | |
Tiger(Tiger), | |
Duck(Duck), | |
} | |
impl Animal { | |
fn sleep(&self) { | |
match self { | |
Animal::Generic(x) => { | |
x.sleep(); | |
}, | |
Animal::Tiger(Tiger { generic_features: x }) => { | |
x.sleep(); | |
}, | |
Animal::Duck(Duck { generic_features: x, .. }) => { | |
x.sleep(); | |
} | |
} | |
} | |
} | |
fn main () { | |
let tiger = Tiger { generic_features: GenericAnimal { age: 10 } }; | |
let duck = Duck { generic_features: GenericAnimal { age: 2 }, color: "white" }; | |
tiger.roar(); | |
duck.fly(); | |
let tiger_animal = Animal::Tiger(tiger); | |
let duck_animal = Animal::Duck(duck); | |
let animal = Animal::Generic(GenericAnimal { age: 2 }); | |
let animals = vec![tiger_animal, duck_animal, animal]; | |
animals.iter().for_each(|x| {x.sleep();}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment