如何在Rust中向枚举结构体内的vec推送值?
我正在尝试弄清楚如何向定义为struct的enum内的vec推送值。
这是设置以及我尝试过的一些方法:
我正在尝试弄清楚如何向定义为struct的enum内的vec推送值。
这是设置以及我尝试过的一些方法:
enum Widget {
Alfa { strings: Vec<String> },
}
fn main() {
let wa = Widget::Alfa { strings: vec![] };
// wa.strings.push("a".to_string());
// no field `strings` on type `Widget`
// wa.Alfa.strings.push("a".to_string());
// no field `Alfa` on type `Widget`
// wa.alfa.strings.push("a".to_string());
// no field `alfa` on type `Widget`
// wa.Widget::Alfa.strings.push("a".to_string());
// expected one of `(`, `.`, `;`, `?`, `}`, or an operator, found `::`
// wa["strings"].push("a".to_string());
// cannot index into a value of type `Widget`
}
创建一个枚举后,是否有可能更新其中的 vec?如果可以,应该如何操作?
(注意:有人建议这是如何在Rust中访问枚举值的重复问题。我看了一下,但它没有解决我的问题。它解决了如何访问值的问题,而不是如何更新它们。这两个问题是相关的,但其他答案中关于访问的解决方案并不适用于更新。)
match
(或者if let
)来告诉编译器哪个变量是被考虑的。 - PitaJ