[英]Why do I get an error when pattern matching a struct-like enum variant with fields?
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 {
key: Vec<u8>,
nr: u8,
mode: OperationMode,
}
impl AES {
pub fn decrypt(&mut self, input: &Vec<u8>) {
match self.mode {
OperationMode::ECB => {},
OperationMode::CBC(_) => {},
};
}
}
The pattern matching at the end of the decrypt
function gives an error: 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 */ }`?
It tells me to look at the output of rustc --explain E0532
for help, which I did.它告诉我查看
rustc --explain E0532
的输出以获得帮助,我做到了。
They show this example of wrong code:他们展示了这个错误代码的例子:
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"), _ => () } }
In this example, the error occurs because State::Failed
has a field which isn't matched.在本例中,发生错误是因为
State::Failed
有一个不匹配的字段。 It should be State::Failed(ref msg)
.它应该是
State::Failed(ref msg)
。
In my case I'm matching the field of my enum because I'm doing OperationMode::CBC(_)
.就我而言,我正在匹配枚举的字段,因为我正在执行
OperationMode::CBC(_)
。 Why does the error happen?为什么会发生错误?
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:也可以看看:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.