Reputation: 401
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?
Upvotes: 3
Views: 2753
Reputation: 399
In cases where you only want to match one variant of an enum, use if let
Upvotes: 0
Reputation: 535
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.
Upvotes: 3