在Rust中如何将值推送到枚举结构中的vec?[duplicate]

5rgfhyps  于 2023-03-12  发布在  其他
关注(0)|答案(2)|浏览(132)

此问题在此处已有答案

How do you access enum values in Rust?(6个答案)
13小时前关门了。
在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`
}

有没有可能在一个emum中的vec被创建后更新它?如果有,该怎么做呢?

brccelvz

brccelvz1#

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

dddzy1tm2#

如果你有一个匹配的手臂(没有意义),你可以这样做:

#[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);
}

相关问题