Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update field in struct-like enum variant

Tags:

enums

struct

rust

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?

like image 511
antoyo Avatar asked Oct 09 '15 16:10

antoyo


1 Answers

Here's one way to do it:

match my_enum {
    Enum::Struct { ref mut field1, .. } => {
        *field1 = 3;
    }
}
like image 160
mbrubeck Avatar answered Sep 20 '22 14:09

mbrubeck