1
votes

I've looked everywhere and cannot find a clear cut example. I want to be able to only match some, not all variants of an enum.

pub enum InfixToken {
    Operator(Operator),
    Operand(isize),
    LeftParen,
    RightParen,
}

So I can perform this in a for loop of tokens:

let x = match token {
    &InfixToken::Operand(c) => InfixToken::Operand(c),
    &InfixToken::LeftParen => InfixToken::LeftParen,
};

if tokens[count - 1] == x {
    return None;
}

How do I compare if the preceding token matches the only two variants of an enum without comparing it to every variant of the enum? x also has to be the same type of the preceding token.

Also, and probably more important, how can I match an operand where isize value doesn't matter, just as long as it is an operand?

1
I've looked everywhere - The Rust Programming Language chapter about match: "The _ acts as a 'catch-all', and will catch all possible values that aren't specified in an arm of match"; this is directly after the intro example, which uses _.Shepmaster

1 Answers

2
votes

You can use _ in patterns to discard a value: InfixToken::Operand(_) => branch. If the whole pattern is _, it will match anything.

To only perform code if specific variants are matched, put that code in the match branch for those variants:

match token {
    &InfixToken::Operand(_) |
    &InfixToken::LeftParen => {
        if tokens[count - 1] == token {
            return None;
        }
    }
    _ => {}
}

The bar (|) is syntax for taking that branch if either pattern is satisfied.