[英]How do I match only some, not all variants of an enum?
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:所以我可以在令牌的 for 循环中执行此操作:
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. x
也必须与前面的标记相同。
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?此外,可能更重要的是,我如何匹配一个操作数,其中
isize
值无关紧要,只要它是一个操作数?
You can use _
in patterns to discard a value: InfixToken::Operand(_) => branch
.您可以在模式中使用
_
来丢弃一个值: 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.如果满足任一模式,则条 (
|
) 是采用该分支的语法。
如果您只想匹配枚举的一个变体,请使用if let
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.