struct Point {
x: f64,
y: f64,
}
enum Shape {
Circle(Point, f64),
Rectangle(Point, Point),
}
let my_shape = Shape::Circle(Point { x: 0.0, y: 0.0 }, 10.0);
我想打印出 circle
的第二个属性,这里是 10.0。
我尝试了 my_shape.last
和 my_shape.second
,但都没有用。
在这种情况下,我应该怎么做才能打印出 10.0?
最佳答案
由于您只对匹配其中一种变体感兴趣,因此可以使用 if let
表达式代替 match
:
struct Point {
x: f64,
y: f64,
}
enum Shape {
Circle(Point, f64),
Rectangle(Point, Point),
}
fn main() {
let my_shape = Shape::Circle(Point { x: 0.0, y: 0.0 }, 10.0);
if let Shape::Circle(_, radius) = my_shape {
println!("value: {}", radius);
}
}
这意味着“如果 my_shape
可以解构为 Circle
,则不对第一个索引执行任何操作,而是将第二个索引的值绑定(bind)到 radius
”。
关于rust - 你如何访问 Rust 中的枚举值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49520931/