Rust, Unions

Mike Code
1 min readMar 22, 2024

--

To define a union just like defining a struct, by using union keyword followed by a name, in curly brackets we can add fields to this union.

All fields in the union share common storage, so write one field can overwrite other fields. It means we only can use one field at a time.

Types of fields in the union need to implement copy trait.

fn main() {
let u1 = MyUnion { f1 : 3};
unsafe {
println!("{}", u1.f1);
println!("{}", u1.f2);
}

}


union MyUnion {
f1: i32,
f2: i16,
}

We create a union with 2 fields of similar data type. we create an instance of this union, assign value 3 to the f1 filed.

To read the data of a union need to be in the unsafe block. So when we printout f1 and f2 fields in the union , it shows the same result of 3 on our screen. ( Fields share same storage , one field will overwrite others)

fn main() {
let mut u1 = MyUnion { f1 : 3};
unsafe {
let f2 = &mut u1.f2;
*f2 = 10;
println!("{}", u1.f1);
println!("{}", u1.f2);
}

}

When we change f2 field’s value, both values of f1 and f2 will change.

If two fields type are not similar , like one field type is i32, another one is &str. When we create an instance of this union, read another filed’s value is undefined behavior.

--

--