[][src]Macro blair_mountain::union

macro_rules! union {
    {
        $(
            $(#[$union_meta:meta])*
            $union_vis:vis union $name:ident$(<$($generic:ident $(: $generic_trait:ty)?$(,)?)*>)?
            $(
                where $($where_generic:ident: $($where_bound:ty)+)*
            )?
            {
                $($member_vis:vis $member:ident: $member_type:ty,)*
            }
        )*
    } => { ... };
}

Define a union. Variants must have trailing commas. Variants must be Copy (without this feature gate). Hash, Default, Debug (and some other traits) can't be derived for unions either, so do not add #[derive] invocations of those above a union.

This macro creates a struct with the name given and the following methods per variant:

  • new_<variant>(val) - creates a new union with the given variant
  • get_<variant> - gets the union's value as the given variant. Unsound if the union is not of that variant.
  • get_<variant>_mut - gets the union's value as the given variant mutable. For soundness, refer to this page
  • set_<variant>(val) - sets the union to the given value. The previous variant should be dropped if need be (ManuallyDrop)
  • into_<variant> - moves the variant out of the union, consuming the union. Unsound if the union is not of that variant.

Note: fields must be Copy.

Example

This example is not tested
use blair_mountain::union;

union! {
    pub union Example {
        pub one: &'static str,
        pub two: u32,
        private: f32,
    }

    pub union GenericExample<T: Copy, U>
       where U: Copy + Clone
    {
       pub one: T,
       pub two: U,
   }
}