简体   繁体   English

我可以匹配所有具有相同值形状的枚举变体吗?

[英]Can I match on all enum variants that have the same shape of their values?

I have an enum:我有一个枚举:

enum MyEnum {
    A(i32),
    B(i32),
    C,
    D,
    // ...
}

Can I match on A and B simultaneously with something like this:我可以同时匹配AB吗?

let a = MyEnum::A(1);
match a {
    _(n) => { // do something for all variants which have one i32 value
    }
    _ => { // ignore the rest
    }
};

Is there any way to accomplish this?有什么办法可以做到这一点? Do I have to match all the variants and apply the same "body" for each?我是否必须匹配所有变体并为每个变体应用相同的“主体”?

No , your desired syntax is not possible;,您想要的语法是不可能的; I don't know how that syntax could work if you had multiple variants with the same count of fields with differing types:我不知道如果您有多个变体,这些变体具有相同数量的不同类型的字段,那么该语法将如何工作:

enum MyEnum {
    A(bool),
    B(String),
}

Do I have to match all the variants and apply the same "body" for each?我是否必须匹配所有变体并为每个变体应用相同的“主体”?

Yes, but you can use patterns to match them in a single match arm:是的,但您可以使用模式在单个匹配中匹配它们 arm:

match a {
    MyEnum::A(n) | MyEnum::B(n) => {
        // use `n`
    }
    _ => {}
};

Or the equivalent if let :或者等效的if let

if let MyEnum::A(n) | MyEnum::B(n) = a {
    // use `n`
}

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

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