问题描述
enum Action {
Fold,Check,Call(i32),Bet(i32),Raise(i32),Post(i32),}
//... other code
//...
infors[seat] = match action {
Action::Fold => Status::Out,Action::Check => infors[seat],Action::Call(x) => infors[seat].incr(x),Action::Bet(x) => infors[seat].incr(x),Action::Raise(x) => infors[seat].incr(x),Action::Post(x) => infors[seat].incr(x),};
是否有一种方法可以对所有具有i32字段的变体进行模式匹配,以便可以合并最后的4行,因为它们都使用x做相同的事情?
本着
的精神Action::_(x) => ...
解决方法
您可以执行以下操作:
match action {
Action::Fold => Status::Out,Action::Check => infors[seat],Action::Call(x) | Action::Bet(x) | Action::Raise(x) | Action::Post(x) => infors[seat].incr(x),}
如果您想缩短所有时间,可以use Action::*
{
// Only import in this block to avoid name conflicts
use Action::*;
match action {
Fold => Status::Out,Check => infors[seat],Call(x) | Bet(x) | Raise(x) | Post(x) => infors[seat].incr(x),}
}
阅读Rust Book Pattern Syntax Chapter了解更多信息