如何对 Box 进行模式匹配以获取结构的属性? [英] How to pattern match a Box to get a struct's attribute?
本文介绍了如何对 Box 进行模式匹配以获取结构的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试访问枚举内装箱结构的属性,但我不知道如何与 std::boxed::Box
I'm trying to access an attribute of a boxed struct inside an enum but I can't figure out how to pattern-match with 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`
访问属性的正确方法是什么?
What is the correct way of accessing the attribute?
推荐答案
您需要取消引用装箱的值,以便您可以访问框内的内容:
You need to dereference the boxed value so that you can access what's inside the box:
match *number {
ArithExp::Num { value } => println!("VALUE = {}", value),
_ => (),
}
这篇关于如何对 Box 进行模式匹配以获取结构的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文