I have this enum type:
enum Animal {
Dog(i32),
Cat(u8),
}
Now I have a function that takes this type as parameter. I know (for some reason) that the input is always a Cat
. I want to achieve this:
fn count_legs_of_cat(animal: Animal) -> u8 {
if let Animal::Cat(c) = animal { c } else { unreachable!() }
}
Can I write this shorter and/or more idiomatic?
Not really. What I have seen is introducing a new
struct
for each enum variant, and then methods on the enum to decompose it:Of course, you don't need the struct and you could just return the
u8
, but that may get hard to track.There's a glimmer of better support for this in the future, however. I think it's the "efficient code reuse" RFC, but better described in the blog post Virtual Structs Part 3: Bringing Enums and Structs Together. The proposal would be to allow
Animal::Cat
to be a standalone type, thus your method could accept anAnimal::Cat
and not have to worry about it.Personally, I almost always prefer to write the infallible code in my inherent implementation and force the caller to panic:
And I'd probably use a
match