我只是在学习 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 let
或 match
有条件地从 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/