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

后端 未结 1 1598
借酒劲吻你
借酒劲吻你 2020-12-17 21:53

I can\'t get rid of an error on this code:

#[derive(PartialEq, Copy, Clone)]
pub enum OperationMode {
    ECB,
    CBC { iv: [u8; 16] },
}

pub struct AES {
         


        
1条回答
  •  眼角桃花
    2020-12-17 22:03

    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?

    0 讨论(0)
提交回复
热议问题