I have a enum:
enum Animals{
Cat("..."),
Dog("...")
Gorilla("...")
}
if the type of enum's parameters are the same,how can I unwrap it
for example, how
let a=Some(5);
let b=a.unwrap()
or
let z=Ok(3)
let r=z.contains(&3);
I have a enum:
enum Animals{
Cat("..."),
Dog("...")
Gorilla("...")
}
if the type of enum's parameters are the same,how can I unwrap it
for example, how
let a=Some(5);
let b=a.unwrap()
or
let z=Ok(3)
let r=z.contains(&3);
You have to write your own methods like unwrap_cat
and unwrap_dog
.
But you can also just do an if let Cat(...) = animal
.
First, remember that unwrap
isn't special. It's just a normal method. So if you want an unwrap on your own type, write such a method.
Then maybe you want something else, like
struct Animal { kind: AnimalKind, name: String }
enum AnimalKind { Cat, Dog, Gorilla }
so that the common things are just a field, not payloads in the different variants.
pub enum Animals<T>{
Cat(T),
Dog(T),
Gorilla(T),
}
impl<T> Animals<T> {
pub fn unwrap(self)->T {
use Animals::*;
match self {
Cat(x)=>x,
Dog(x)=>x,
Gorilla(x)=>x,
}
}
}