gpt4 book ai didi

rust - 与枚举的构造函数匹配的模式

转载 作者:行者123 更新时间:2023-11-29 08:22:55 25 4
gpt4 key购买 nike

我有一个枚举:

pub enum Enum1 {
A(String),
B(i64),
C(f64)
}

我如何对 A 进行模式匹配?也就是说,我想得到它的String值。我试过这个:

match optionMyEnum {
Some(A(x: String)) => ...

并得到了大量的编译错误。

最佳答案

The Rust Programming Language有一个完整的 section on matching .我强烈鼓励您阅读该部分(以及整本书)。该文档投入了大量时间和精力。

您只需指定一个要绑定(bind)的名称。无需写出类型:

pub enum Enum {
A(String),
B(i64),
C(f64),
}

fn main() {
let val = Enum::A("hello".to_string());

match val {
Enum::A(x) => println!("{}", x),
_ => println!("other"),
}
}

在许多情况下,您会希望绑定(bind)到值的引用:

Enum::A(ref x) => println!("{}", x),

关于rust - 与枚举的构造函数匹配的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36984644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com