简体   繁体   中英

How can I return None when a given enum is not a certain variant?

I have the following enum defined:

#[derive(Debug, Copy, Clone)]
struct Core;

#[derive(Debug, Copy, Clone)]
struct Mem;

#[derive(Debug, Copy, Clone)]
pub enum Atag {
    Core(Core),
    Mem(Mem),
    Cmd(&'static str),
    Unknown(u32),
    None,
}

I would like to implement a function on this enum which "filters out" certain enum values. I have the following:

impl Atag {
    /// Returns `Some` if this is a `Core` ATAG. Otherwise returns `None`.
    pub fn core(self) -> Option<Core> {
        match self {
            Atag::Core => Some(self),
            _ => None
        }
    }
}

I'm not sure why, but the compiler complains:

error[E0532]: expected unit struct/variant or constant, found tuple variant `Atag::Core`
  --> src/main.rs:17:13
   |
17 |             Atag::Core => Some(self),
   |             ^^^^^^^^^^ not a unit struct/variant or constant
help: possible better candidate is found in another module, you can import it into scope
   |
1  | use Core;
   |

I also tried a comparison approach:

pub fn core(self) -> Option<Core> {
    if self == Atag::Core {
        Some(self)
    } else {
        None
    }
}

But the compiler complains:

error[E0369]: binary operation `==` cannot be applied to type `Atag`
  --> src/main.rs:20:12
   |
20 |         if self == Atag::Core {
   |            ^^^^^^^^^^^^^^^^^^
   |
   = note: an implementation of `std::cmp::PartialEq` might be missing for `Atag`

I think this is just a limitation of the pattern matching and is designed to prevent unexpected behavior.

The full "definition" of an Atag with type Core is Atag::Core(raw::Core) . Obviously, the contents of the Core are irrelevant to you, but the compiler needs to know that everything is "accounted for" because the compiler is a stickler for the rules. The easiest way to get around this is to use the "anything pattern", _ , much like you did to match non- Core variants.

impl Atag {
    /// Returns `Some` if this is a `Core` ATAG. Otherwise returns `None`.
    pub fn core(self) -> Option<Core> {
        match self {
            // The compiler now knows that a value is expected,
            // but isn't necessary for the purposes of our program.
            Atag::Core(_) => Some(self),
            _ => None
        }
    }
}

To ignore multiple values, you'd use Something::Foo(_, _) - one underscore for each value in the variant, or Something::Foo(..) to ignore everything.

Remember that, unlike in some other languages, a Rust enum is not "just" a collection of different types. Data associated with an enum value is a part of it, just like the fields of a structure. So self == Atag::Core isn't a meaningful statement because it ignores the data associated with a Core . A Foo(0) is different than a Foo(12) , even if they're both of the Foo variant.

I'd also like to point out if let , which is - as far as I can tell - the closest option to a standard if statement without defining a custom is_core function on Atag (which, given the existence of match and if let , is basically unnecessary).

impl Atag {
    /// Returns `Some` if this is a `Core` ATAG. Otherwise returns `None`.
    pub fn core(self) -> Option<Core> {
        if let Atag::Core(_) = self {
            Some(self)
        } else {
            None
        }
    }
}

I needed something like this to chain functions together nicely. In that case, you want to return the unwrapped core type, rather than just the enum.

I also found it easier to not consume the input, and so accepted a &self argument an returned an Option<&Core> . But you can have both.

The Rust convention has as_X as the reference-based conversion and into_X as the conversion that consumes the value. For example:

impl Atag {
    fn as_core(&self) -> Option<&Core> {
        if let Atag::Core(ref v) = self {
            Some(v)
        } else {
            None
        }
    }
    fn into_core(self) -> Option<Core> {
        if let Atag::Core(v) = self {
            Some(v)
        } else {
            None
        }
    }
}

fn main() {
    let c = Atag::Core(Core {});
    let m = Atag::Mem(Mem {});
    assert_eq!(c.as_core().map(|cc| "CORE_REF"), Some("CORE_REF"));
    assert_eq!(m.as_core().map(|cc| "CORE_REF"), None);
    // Consume c - we cant use it after here...
    assert_eq!(c.into_core().map(|cc| "NOM NOM CORE"), Some("NOM NOM CORE"));
    // Consume m - we cant use it after here...
    assert_eq!(m.into_core().map(|cc| "NOM NOM CORE"), None);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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