如何将值推送到Rust中枚举 struct 中的vec?

我正在try 弄清楚如何将值推送到定义为 struct 的枚举内的vec.

以下是我try 过的一些设置:

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`
}

是否可以在eMum中创建VEC后对其进行更新?如果是这样的话,我们该如何go 做呢?

推荐答案

您不能直接访问枚举变量上的字段,因为编译器只知道值是枚举类型(Widget),而不知道它具有哪个枚举变量.您必须对枚举进行 struct 分析,例如使用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`.
}

或者,您也可以改用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!()
}

Rust相关问答推荐

如果A == B,则将Rc A下推到Rc B

在自身功能上实现类似移动的行为,以允许通过大小的所有者进行呼叫(&;mut;self)?

使用 struct 外部的属性来改变 struct 的原始方式

自定义结果枚举如何支持`?`/`FromResidual`?

为什么HashMap::get和HashMap::entry使用不同类型的密钥?

try 实现线程安全的缓存

UnsafeCell:它如何通知 rustc Select 退出基于别名的优化?

Rust中的标记特征是什么?

我可以在 Rust 中 serde struct camel_case 和 deserde PascalCase

max(ctz(x), ctz(y)) 有更快的算法吗?

在不安全的 Rust 中存储对 struct 内部数据的静态引用是否合法?

为什么数组不像向量那样在 for 块之后移动?

将 Futures 的生命周期特征绑定到 fn 参数

如何在 Rust 中编写涉及异步的重试函数

我如何将 google_gmail1::Gmail> 传递给线程生成?

如何为返回正确类型的枚举实现 get 方法?

为什么我可以在没有生命周期问题的情况下内联调用 iter 和 collect?

为什么-x试图解析为文字并在声明性宏中失败?

为什么 Rust 标准库同时为 Thing 和 &Thing 实现特征?

为什么当borrow 变量发生变化时,borrow 变量不会改变?