Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Uniões

Unions são como enums, mas você mesmo precisa rastrear o campo ativo:

#[repr(C)]
union MyUnion {
    i: u8,
    b: bool,
}

fn main() {
    let u = MyUnion { i: 42 };
    println!("int: {}", unsafe { u.i });
    println!("bool: {}", unsafe { u.b }); // Comportamento indefinido!
}
This slide should take about 5 minutes.

Unions raramente são necessárias no Rust, pois geralmente você pode usar um enum. Elas são ocasionalmente necessárias para interagir com as APIs da biblioteca C.

Se você deseja apenas reinterpretar os bytes como um tipo diferente, você provavelmente deveria usar std::mem::transmute ou um wrapper seguro como o crate zerocopy.