Search code examples
enumsrust

Sharing a common value in all enum values


I have the following code where every variant of the enum Message has a Term value associated with it:

type Term = usize;
pub enum Message {
    AppendRequest(Term),
    AppendResponse(Term),
    VoteRequest(Term),
    VoteResponse(Term),
}

impl Message {
    pub fn term(&self) -> Term {
        match *self {
            Message::AppendRequest(term)  => term,
            Message::AppendResponse(term) => term,
            Message::VoteRequest(term) => term,
            Message::VoteResponse(term) =>term,
        }
    }
}

I want to, given a Message be able to get its term without having to deconstruct the actual Message value I have. The best I could come up with was creating a public function that unpacked the value for me, but this feels clunky. If I ever add a new enum value, I'm going to have to remember to update match statement in the term function.

Is there a more succinct/ergonomic way to express the code above? Is there some way to say "hey, every value for this enum will have also have a Term value associated with it.


Solution

  • Is there some way to say "hey, every value for this enum will have also have a Term value associated with it.

    No. This is usually handled by splitting the enum into two parts, with a struct containing all the common parts:

    pub struct Message {
        term: Term,
        kind: MessageKind,
    }
    
    pub enum MessageKind {
        AppendRequest,
        AppendResponse,
        VoteRequest,
        VoteResponse,
    }