你如何在 Rust 中访问枚举值? [英] How do you access enum values in Rust?

查看:40
本文介绍了你如何在 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,但都没有奏效.

I want to print out circle's second property, which is 10.0 here. I tried my_shape.last and my_shape.second, but neither worked.

在这种情况下,我应该怎么做才能打印出 10.0?

What should I do in order to print out 10.0 in this case?

推荐答案

您可以使用模式匹配:

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);

    match my_shape {
        Shape::Circle(_, value) => println!("value: {}", value),
        _ => println!("Something else"),
    }
}

示例输出:

value: 10

这篇关于你如何在 Rust 中访问枚举值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆