0

I have an enum:

pub enum Enum1 {
    A(String),
    B(i64),
    C(f64)
}

How can I do pattern matching against A? That is, I want to get its String value. I've tried this:

match optionMyEnum {
  Some(A(x: String)) => ...

and got plenty of the compile errors.

1
  • match optionMyEnum — note that Rust uses snake_case for variable names, not camelCase. Commented May 2, 2016 at 14:21

1 Answer 1

4

The Rust Programming Language has an entire section on matching. I'd highly encourage you to read that section (and the entire book). A lot of time and effort has gone into that documentation.

You simply specify a name to bind against. There's no need to write out types:

pub enum Enum {
    A(String),
    B(i64),
    C(f64),
}

fn main() {
    let val = Enum::A("hello".to_string());

    match val {
        Enum::A(x) => println!("{}", x),
        _ => println!("other"),
    }
}

In many cases, you will want to bind to a reference to the values:

Enum::A(ref x) => println!("{}", x),
Sign up to request clarification or add additional context in comments.

Comments