Update field in struct-like enum variant

2019-06-24 05:12发布

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条回答
地球回转人心会变
2楼-- · 2019-06-24 05:50

Here's one way to do it:

match my_enum {
    Enum::Struct { ref mut field1, .. } => {
        *field1 = 3;
    }
}
查看更多
登录 后发表回答