rust - 为什么我不能直接访问枚举字段?

标签 rust enums

我只是在学习 Rust。
所以我知道这有效:

enum Animal {
    Cat { name: String, weight: f64 }
}

fn main() {
    let a = Animal::Cat { name: "Spotty".to_string(), weight: 2.7 };
    match a {
        Animal::Cat{name, weight} => { println!("Cat n={} w={}", name, weight); }
    }
}
但为什么我不能像这样直接从枚举字段分配:
    ...
    let wt = a.weight;
还是我使用了错误的语法?还是因为 Rust 不能保证 Animal实例的类型为 Cat ?
是使用 match 访问枚举结构或元组变体实例的字段的唯一方法?

最佳答案

这是因为weight不属于 Animal枚举,它是 Cat 的一部分枚举的类型。假设将来您添加了另一种没有体重信息的动物:

enum Animal {
    Cat { name: String, weight: f64 },
    Insect { species: String, height: f64 },
}
然后a.weight并不总是有值(value)。您可以使用 if letmatch有条件地从 enum 获取数据如果存在:
if let Animal::Cat { weight, .. } = a {
    println!("Your cat weights {} kg.", weight);
} else {
    println!("get a cat");
};

关于rust - 为什么我不能直接访问枚举字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66602152/

相关文章:

swift - 具有相同案例名称且具有不同类型关联值的枚举

c++ - 枚举的复合赋值运算符真的应该根据它们相关的算术运算符来定义吗?

kotlin - 从关联值初始化枚举

rust - 将字符转换为大写

rust - 如何限制struct的构造?

compiler-errors - 为什么使用 f32::consts::E 会给出错误 E0223 但 std::f32::consts::E 不会?

syntax - 如何以干净的方式混合 bool 比较和 'if let' 语句?

C# "Enum"序列化 - 反序列化为静态实例

c++ - 多个输出运算符?

rust mod 声明的不一致