January 2019
Beginner to intermediate
554 pages
13h 31m
English
For interoperability with C code, Rust also supports the union type, which maps directly to a C union. Unions are unsafe to read from. Let's see an example of how to create and interact with them:
// unions.rs#[repr(C)]union Metric { rounded: u32, precise: f32,}fn main() { let mut a = Metric { rounded: 323 }; unsafe { println!("{}", a.rounded); } unsafe { println!("{}", a.precise); } a.precise = 33.3; unsafe { println!("{}", a.precise); }}
We created a union type, Metric, that has two fields rounded and precise, and represents some measurement. In main, we initialize an instance of it in the a variable.
We can only initialize one of the variables, otherwise the compiler complains with the following message:
error: union expressions ...
Read now
Unlock full access