如何将值推送到 Rust 中枚举结构内的 vec?
我试图弄清楚如何将值推送到定义为结构的枚举内的 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`
}
Run Code Online (Sandbox Code Playgroud)
创建 emum 后是否可以更新它?如果是这样,该怎么办呢?
(注意:有人建议这是How do you access enum value in Rust?的重复。我看了它,但它没有解决我的问题。它解决了如何访问值,而不是如何更新它们。这两个事情是相关的,但另一个访问答案中的解决方案不支持更新。)
您无法直接访问枚举变体上的字段,因为编译器只知道该值属于枚举类型 ( Widget
),而不知道它具有枚举的哪个变体。您必须解构枚举,例如使用match
:
let mut wa = Widget::Alfa { strings: vec![] };
match &mut wa {
Widget::Alfa { strings /*: &mut Vec<String> */ } => {
strings.push("a".to_string());
}
// if the enum has more variants, you must have branches for these as well.
// if you only care about `Widget::Alfa`, a wildcard branch like this is often a
// good choice.
_ => unreachable!(), // panics if ever reached, which we know in this case it won't
// because we just assigned `wa` before the `match`.
}
Run Code Online (Sandbox Code Playgroud)
或者你可以使用if let
:
let mut wa = Widget::Alfa { strings: vec![] };
if let Widget::Alfa { strings } = &mut wa {
strings.push("a".to_string());
} else {
// some other variant than `Widget::Alfa`, equivalent to the wildcard branch
// of the `match`. you can omit this, which would just do nothing
// if it doesn't match.
unreachable!()
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
220 次 |
最近记录: |