【发布时间】:2021-03-12 14:50:03
【问题描述】:
我只是在学习 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 访问枚举结构或元组变体实例的字段的唯一方法吗?
【问题讨论】: