简体   繁体   English

有没有办法匹配 rust 中枚举的所有变体?

[英]Is there a way to match on all variants of an enum in rust?

Is there something that is equivalent to this:有没有与此等效的东西:

enum ABC {
    A(u32),
    B(i32),
    C(f64),
}

fn main() {
    let abc = ABC::A(42);

    match abc {
        _(foo) => foo,
    }
}

The reason why I'm asking is that sometimes, I want to use an enum for the different possible types, but most cases I need to handle the data in the enum variants the same exact way.我问的原因是有时,我想为不同的可能类型使用枚举,但大多数情况下我需要以完全相同的方式处理枚举变体中的数据。

If you want to match against all possible variants and perform a common action you can write a macro for it and reduce code repetition:如果您想匹配所有可能的变体并执行常见操作,您可以为其编写宏并减少代码重复:

enum ABC {
    A(u32),
    B(i32),
    C(f64),
}

#[macro_use]
macro_rules! per_letter {
    ($val:expr, $pattern:pat => { $res:expr }) => (
        match $val {
            $crate::ABC::A($pattern) => $res,
            $crate::ABC::B($pattern) => $res,
            $crate::ABC::C($pattern) => $res,
        }
    )
}

impl ABC {
    pub fn print_inner(&self) {
        per_letter!(self, letter => {println!("{}", letter)});
    }
    pub fn print_quad(&self) {
        per_letter!(self, letter => {println!("{}", *letter**letter)});
    }
}

Note that this is limited.请注意,这是有限的。 You can't have multiple possible return types without wrapping them in an enum.如果不将它们包装在枚举中,就不能有多种可能的返回类型。 But it's still useful if your inner types share a common functionality.但是,如果您的内部类型共享一个通用功能,它仍然很有用。

fn main() {
    let foo = ABC::A(2);
    foo.print_inner();
    foo.print_quad();
}

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

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