3

My simplified code:

enum MyEnum {
    A(u32),
    B(String),
    C(i32),
}

pub struct MyStruct {
    aa: String,
    bb: u16,
    my_enum: MyEnum,
}

let my_struct1 = MyStruct { /*...*/ };

How can I get the underlying variable of my_struct1.my_enum which could be a u32, String or i32. Is it only by pattern matching?

1

1 Answer 1

4

Pattern matching is not limited to match. If you only care about one type of the variant, you can also do

if let MyEnum::B(s) = my_struct1.my_enum {
    println!("{}", s);
}

The println line will only be run when the value of my_struct1.my_enum is actually of type MyEnum::B. Rust enum is safe. It is not like C union, which you can unsafely access the underlying value as you wish no matter which type the value actually is.

Sign up to request clarification or add additional context in comments.

2 Comments

if they all had the same underlying type, say, u32 like A does, how would get that variable?
@OskarK. Then you will need to use match: let v = match my_struct1.my_enum { MyEnum::A(a) => a, MyEnum::B(b) => b, MyEnum::C(c) => c };.