rust - 你如何访问 Rust 中的枚举值?

标签 rust

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.lastmy_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/

相关文章:

rust - 在 Rust 中返回可变引用

rust - 我怎样才能对 Option<String> 进行模式匹配?

rust - 为什么在使用 futures::ok 时会出现错误 "cannot infer type"?

rust - 如何将HashSet <&String>转换为HashSet <String>

rust - 装箱选项的简洁方法

if-statement - 何时在 Rust 中使用 `std::cmp::ordering` 而不是 `if` 语句

multithreading - 将矩阵 (Vec<Vec<f64>>) 只读传递给多个线程

performance - 我可以在每次除法时禁用检查零除法吗?

recursion - 如何构建用于递归遍历文件树的迭代器?

c++ - 无法使用bindgen进行llvm绑定(bind)