Search code examples
rustenumsmatchtraits

Is there a better way access a same-type enum value than a match?


Is there a better way to access the contents of an Enum that in the various cases shares the same variable type?
At the moment I have solved it this way:

enum Token<'a> {
    Word(&'a str),
    Reserved(&'a str),
    Whitespace(&'a str),
}

impl<'a> ToString for Token<'a> {
    fn to_string(&self) -> String {
        match self {
            Self::Word(str) | Self::Reserved(str) | Self::Whitespace(str) => str.to_string(),
        }
    }
}

Solution

  • Not with this implementation. But you could (and maybe should) instead have

    enum TokenKind {
        Word,
        Reserved,
        Whitespace,
    }
    
    struct Token<'a> {
      string: &'a str, 
      kind: TokenKind
    }
    

    This is more extensible, and less code duplication.