rust - 如何对 Box 进行模式匹配以获取结构的属性?
问题描述
我正在尝试访问枚举内的盒装结构的属性,但我不知道如何与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`
访问属性的正确方法是什么?
解决方案
您需要取消引用装箱的值,以便您可以访问框内的内容:
match *number {
ArithExp::Num { value } => println!("VALUE = {}", value),
_ => (),
}
推荐阅读
- c# - SQL 在 C# 之间选择带有 OR 的过滤器
- css - 对话框中的 Primefaces 8.0 日历弹出窗口相对于父屏幕滚动位置定位
- r - R中带有条件的for循环
- java - Java,Maven - 文件覆盖数据而不是将数据附加到它
- react-native - FormData Data.Append 在 react-native 中没有向后端发送任何内容
- autohotkey - 延迟像素搜索
- r - 如何在 R Markdown 中选择特定选项卡?
- python - Python 或 Unix/Bash。将大数据框拆分为单独的列,保留前 n 列
- c++ - 在多个文件之间共享变量时如何理解extern的用法?
- c++ - 如何将 uintptr_t 值设置为非 uintptr_t 函数的地址?