为什么在使用字段匹配类似结构的枚举变体的模式时会出现错误?

问题描述 投票:3回答:1

我无法摆脱这段代码的错误:

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

pub struct AES {
    key: Vec<u8>,
    nr: u8,
    mode: OperationMode,
}

impl AES {
    pub fn decrypt(&mut self, input: &Vec<u8>) {
        match self.mode {
            OperationMode::ECB => {},
            OperationMode::CBC(_) => {},
        };
    }
}

decrypt函数末尾的模式匹配给出错误:

error[E0532]: expected tuple struct/variant, found struct variant `OperationMode::CBC`
  --> src/main.rs:17:13
   |
17 |             OperationMode::CBC(_) => {},
   |             ^^^^^^^^^^^^^^^^^^ did you mean `OperationMode::CBC { /* fields */ }`?

它告诉我看看rustc --explain E0532的输出求助,我做了。

他们展示了错误代码的示例:

enum State {
    Succeeded,
    Failed(String),
}

fn print_on_failure(state: &State) {
    match *state {
        // error: expected unit struct/variant or constant, found tuple
        //        variant `State::Failed`
        State::Failed => println!("Failed"),
        _ => ()
    }
}

在此示例中,发生错误是因为State::Failed具有不匹配的字段。它应该是State::Failed(ref msg)

在我的情况下,我匹配我的枚举领域,因为我正在做OperationMode::CBC(_)。为什么会发生错误?

enums rust pattern-matching
1个回答
12
投票

枚举变体有三种可能的语法:

  • 单元 enum A { One }
  • 元组 enum B { Two(u8, bool) }
  • 结构 enum C { Three { a: f64, b: String } }

模式匹配时必须使用相同的语法作为变体定义的语法。

在这种情况下,你需要花括号和.. catch-all:

OperationMode::CBC { .. } => {}

也可以看看:

© www.soinside.com 2019 - 2024. All rights reserved.