繁体   English   中英

匹配包含附加数据的枚举的所有变体

[英]match all variants of an enum that contain attached data

我只是在学习和编写一个带有以下代码的小型扑克程序:

enum Action {
    Fold,
    Check,
    Call(i32),
    Bet(i32),
    Raise(i32),
    Post(i32),
}

// ...

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 章节以获取更多信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM