Cannot access 0 under my enum

I have an enum with a value inside but I try to access .0 i get error message saying 0 doesnt exist under my enum

pub enum Type<'name> {
    A(&'name str),
    B(&'name str),
    C(&'name str),
    D(&'name str),
}
impl<'name> Display for Type<'name> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.0) 
    }
}
error[E0609]: no field `0` on type `&Type<'name>`
  --> src/premium/mod.rs:47:26
   |
47 |         f.write_str(self.0)
   |                          ^

The enum itself is not like a tuple, you will need to do something like the following:

match self {
    Self::A(name) => name,
    Self::B(name) => name,
    Self::C(name) => name,
    Self::D(name) => name,
}

Alternatively, you could extract the common parts into a struct:

enum TypeKind {
    A,
    B,
    C,
    D,
}

struct Type<'name> {
    name: &'name str,
    kind: TypeKind
}

// now you can do this, no matter the kind
self.name
5 Likes

There's no built in syntax to handle enums where all the variants have the same payload. You're going to have to be more explicit with a match or write a helper method. For example:

impl<'a> Type<'a> {
    fn inner(&self) -> &str {
        match self {
            Type::A(x) | Type::B(x) | Type::C(x) | Type::D(x) => x,
        }
    }
}

(Then use self.inner() elsewhere, like in your Display implementation.)

2 Likes

Ah, forgot about the nifty or patterns. Still haven't had a chance to play enough with them :stuck_out_tongue:

I also ended up doing it this way but for my usecase it seems like @Lonami's way makes more sense

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.