Why do I get an error when pattern matching a struct-like enum variant with fields?

Enum variants have three possible syntaxes:

  • unit

    enum A { One }
    
  • tuple

    enum B { Two(u8, bool) }
    
  • struct

    enum C { Three { a: f64, b: String } }
    

You have to use the same syntax when pattern matching as the syntax the variant was defined as:

  • unit

    match something {
        A::One => { /* Do something */ }
    }
    
  • tuple

    match something {
        B::Two(x, y) => { /* Do something */ }
    }
    
  • struct

    match something {
        C::Three { a: another_name, b } => { /* Do something */ }
    }
    

Beyond that, you can use various patterns that allow ignoring a value, such as _ or ... In this case, you need curly braces and the .. catch-all:

OperationMode::CBC { .. } => { /* Do something */ }

See also:

  • Ignoring Values in a Pattern in The Rust Programming Language
  • Appendix B: Operators and Symbols in The Rust Programming Language
  • How to match struct fields in Rust?

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)