Now that you have an overview of enums and it's possible variants, let's have a more complex example.
In this challenge, you will create an Animal enum that demonstrates all three types of variants.
Create an enum Animal with the following variants:
Unit Struct Variant:
Dog — represents a generic dog.Tuple Struct Variant:
Cat(String) — represents a cat, where the String contains the cat's name.Named Field Struct Variant:
Bird { species: String, can_fly: bool } — represents a bird with its species and whether it can fly.Write a function describe_animal that takes a reference to an Animal and returns a String description based on the variant:
Dog, return "A friendly dog.".Cat(name), return "A cat named {name}.".Bird { species, can_fly }, return:
"A {species} that can fly." if can_fly is true."A {species} that cannot fly." if can_fly is false.match statement to destructure tuple and named field variants.format! makes it easy to include dynamic values in your description.Now that you have an overview of enums and it's possible variants, let's have a more complex example.
In this challenge, you will create an Animal enum that demonstrates all three types of variants.
Create an enum Animal with the following variants:
Unit Struct Variant:
Dog — represents a generic dog.Tuple Struct Variant:
Cat(String) — represents a cat, where the String contains the cat's name.Named Field Struct Variant:
Bird { species: String, can_fly: bool } — represents a bird with its species and whether it can fly.Write a function describe_animal that takes a reference to an Animal and returns a String description based on the variant:
Dog, return "A friendly dog.".Cat(name), return "A cat named {name}.".Bird { species, can_fly }, return:
"A {species} that can fly." if can_fly is true."A {species} that cannot fly." if can_fly is false.match statement to destructure tuple and named field variants.format! makes it easy to include dynamic values in your description.