开发者

Pattern match on enum type don't care about arguments

开发者 https://www.devze.com 2022-12-07 21:26 出处:网络
enum Foo { Bar(usize, usize), Baz(isize), } impl Operator { fn value(&self) -> usize { use Foo::*; match (self) {
enum Foo {
  Bar(usize, usize),
  Baz(isize),
}

impl Operator {
    fn value(&self) -> usize {
        use Foo::*;
        match (self) {
            Bar(_) => 1,
            Baz(_) => 2,
        }
    }
}

neither Bar(_), Bar, nor Bar() work.

I just want to pattern-match the enum type, and the arguments don't matter at all. I would prefer to not have to remember how many _ I need to put for each enum variant, and not have to change these pa开发者_如何学Gotterns in the case that the enum definition changes.


Since Bar has two arguments you either have to match them both:

match self {
       Bar(_, _) => 1,
       Baz(_) => 2,
}

or use ..

match self {
    Bar(..)
    Baz(_) => 2,
}
0

精彩评论

暂无评论...
验证码 换一张
取 消