在Rust中,如何将值推送到枚举结构体内的vec?

6
如何在Rust中向枚举结构体内的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中访问枚举值的重复问题。我看了一下,但它没有解决我的问题。它解决了如何访问值的问题,而不是如何更新它们。这两个问题是相关的,但其他答案中关于访问的解决方案并不适用于更新。)


1
你需要使用 match(或者 if let)来告诉编译器哪个变量是被考虑的。 - PitaJ
2个回答

6

你不能直接访问枚举变量的字段,因为编译器只知道该值是枚举类型(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`.
}

或者你可以使用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!()
}

1
如果您有一个匹配的手臂(没有感觉),则可以像这样做:
#[derive(Debug)]
enum Widget {
    Alfa { strings: Vec<String> },
}

fn main() {
    let mut wa = Widget::Alfa { strings: vec![] };

    let Widget::Alfa { strings } = &mut wa;
    
    strings.push("X".to_string());
    strings.push("Y".to_string());

    println!("{:?}", wa);
}

或者使用matchif let):

#[derive(Debug)]
enum Widget {
    Alfa { strings: Vec<String> },
    Beta { string: Vec<String> }
}

fn main() {
    let mut wa = Widget::Alfa { strings: vec![] };

    if let Widget::Alfa { strings } = &mut wa {
        strings.push("X".to_string());
        strings.push("Y".to_string());
    }

    println!("{:?}", wa);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接