How to unwrap own enum

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.

3 Likes

Here's a crate for that (which I haven't reviewed).

1 Like

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.

8 Likes
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,
        }
    }
}
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.