Update field in struct-like enum variant

蹲街弑〆低调 提交于 2019-12-23 12:37:17

问题


I am able to use the struct update syntax with a single struct, but I am not able to use it with a struct-like enum variant. Neither can I update a field from a struct-like enum variant with the dot syntax.

For instance:

enum Enum {
    Struct {
        field1: i32,
        field2: i32,
    }
}

fn main() {
    let mut my_enum = Enum::Struct {
        field1: 1,
        field2: 2,
    };

    my_enum = Enum::Struct {
        field1: 1,
        .. my_enum
    };

    my_enum = match my_enum {
        strct@Enum::Struct { field1, field2 } => Enum::Struct {
            field1: 1,
            .. strct
        },
    };
}

Both ways give me an error:

functional record update syntax requires a struct

This code:

my_enum.field1 = 3;

gives me the following error:

attempted access of field `field1` on type `Enum`, but no field with that name was found

How can I update a field from a struct-like enum variant?


回答1:


Here's one way to do it:

match my_enum {
    Enum::Struct { ref mut field1, .. } => {
        *field1 = 3;
    }
}


来源:https://stackoverflow.com/questions/33043280/update-field-in-struct-like-enum-variant

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!