当我不关心它包含什么值时,如何在`if`语句中使用枚举? [英] How do I use an enum in an `if` statement when I don't care what value it contains?

查看:115
本文介绍了当我不关心它包含什么值时,如何在`if`语句中使用枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个枚举:

#[derive(PartialEq, Eq)]
enum Foo {
    A,
    B(usize),
}

我可以使用它在中,如果涉及其他逻辑的语句,如 baz

I can use it in if statements involving other logic like baz:

fn bar(foo: &Foo, baz: bool) {
    if foo == &Foo::B(3) || baz {
        println!("Do stuff")
    }
}

然而,这不会编译:

fn bar(foo: &Foo, baz: bool) {
    if foo == &Foo::B(_) || baz {
        println!("Do stuff")
    }
}

当我不在乎 B 包含哪个值时,如何在 if 语句中使用它? / p>

How do I use it in an if statement when I don't care what value B contains?

推荐答案

在这种情况下使用匹配可能更容易:

It's probably easier to use a match in this case:

fn do_stuff() {
    println!("Do stuff")
}

fn bar(foo: &Foo, baz: bool) {
    match foo {
        &Foo::B(_) => do_stuff(),
        _ => {
            if baz {
                do_stuff();
            }
        }
    }
}

或者使用如果让

fn bar(foo: &Foo, baz: bool) {
    if let &Foo::B(_) = foo {
        do_stuff();
    } else {
        if baz {
            do_stuff();
        }
    }
}

我不确定你可以很容易地把它全部拉到一个条件,这让你不幸重复 do_stuff

I'm not sure you can pull it all into a single condition easily, which makes you repeat do_stuff unfortunately.

这篇关于当我不关心它包含什么值时,如何在`if`语句中使用枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆