我正在尝试访问枚举中盒装结构的属性,但我不知道如何与std::boxed::Box
进行模式匹配
enum ArithExp {
Sum {
lhs: Box<ArithExp>,
rhs: Box<ArithExp>,
},
Mul {
lhs: Box<ArithExp>,
rhs: Box<ArithExp>,
},
Num {
value: f64,
},
}
fn num(value: f64) -> std::boxed::Box<ArithExp> {
Box::new(ArithExp::Num { value })
}
let mut number = num(1.0);
match number {
ArithExp::Num { value } => println!("VALUE = {}", value),
}
我收到以下错误:
error[E0308]: mismatched types
--> src/main.rs:22:9
|
22 | ArithExp::Num { value } => println!("VALUE = {}", value),
| ^^^^^^^^^^^^^^^^^^^^^^^ expected struct `std::boxed::Box`, found enum `main::ArithExp`
|
= note: expected type `std::boxed::Box<main::ArithExp>`
found type `main::ArithExp`
访问属性的正确方法是什么?
答案 0 :(得分:3)
您无需将enum
装箱:
fn num(value: f64) -> ArithExp {
ArithExp::Num { value }
}
编译器将给您的错误是关于在enum
臂中提供其余match
个变体。您可以提供每个臂,也可以提供一个_
臂……这意味着“其他”:
let mut number = num(1.0);
match number {
ArithExp::Num { value } => println!("VALUE = {}", value),
_ => (), // do nothing if its something else
}
答案 1 :(得分:3)
您需要取消引用装箱的值,以便可以访问包装箱中的内容:
match *number {
ArithExp::Num { value } => println!("VALUE = {}", value),
_ => (),
}