Movatterモバイル変換


[0]ホーム

URL:


union

Keywordunion 

Source
Expand description

TheRust equivalent of a C-style union.

Aunion looks like astruct in terms of declaration, but all of itsfields exist in the same memory, superimposed over one another. For instance,if we wanted some bits in memory that we sometimes interpret as au32 andsometimes as anf32, we could write:

unionIntOrFloat {    i: u32,    f: f32,}letmutu = IntOrFloat { f:1.0};// Reading the fields of a union is always unsafeassert_eq!(unsafe{ u.i },1065353216);// Updating through any of the field will modify all of themu.i =1073741824;assert_eq!(unsafe{ u.f },2.0);

§Matching on unions

It is possible to use pattern matching onunions. A single field name mustbe used and it must match the name of one of theunion’s field.Like reading from aunion, pattern matching on aunion requiresunsafe.

unionIntOrFloat {    i: u32,    f: f32,}letu = IntOrFloat { f:1.0};unsafe{matchu {        IntOrFloat { i:10} =>println!("Found exactly ten!"),// Matching the field `f` provides an `f32`.IntOrFloat { f } =>println!("Found f = {f} !"),    }}

§References to union fields

All fields in aunion are all at the same place in memory which meansborrowing one borrows the entireunion, for the same lifetime:

unionIntOrFloat {    i: u32,    f: f32,}letmutu = IntOrFloat { f:1.0};letf =unsafe{&u.f };// This will not compile because the field has already been borrowed, even// if only immutablyleti =unsafe{&mutu.i };*i =10;println!("f = {f} and i = {i}");

See theReference for more information onunions.


[8]ページ先頭

©2009-2026 Movatter.jp