[][src]Macro trait_union::trait_union

trait_union!() { /* proc-macro */ }

Macro that generates a trait-union type

Syntax

Each invocation of the macro can generate an arbitrary number of trait-union types.

The syntax of each declaration is as follows:

ATTRIBUTE* VISIBILITY? 'union' NAME GENERICS? ':' TRAIT_BOUNDS ('where' WHERE_CLAUSE)? '=' TYPE ('|' TYPE)* '|'? ';'

? denotes an optional segment. * denotes 0 or more repetitions.

For example:

This example is not tested
/// MyUnion trait-union
pub(crate) union MyUnion<'a, T: 'a>: Debug+'a where T: Debug+Copy = &'a str | Option<T>;

Trait bounds

The TRAIT_BOUNDS segment denotes the trait that the trait-union will deref to. As such, it must contain at least one trait, at most one non-auto trait, and 0 or more lifetimes.

For example:

This example is not tested
Debug+Copy+'a // OK
'a            // Error: No trait
Debug+Display // Error: More than one non-auto trait

If you do not provide a lifetime, the 'static lifetime will be added automatically. That is, Debug is the same as Debug+'static. For example

This example is not tested
union MyUnion<'a>: Debug = &'a str;

will not compile because &'a str is not 'static. Write

This example is not tested
union MyUnion<'a>: Debug+'a = &'a str;

instead.

Output

The macro generates a struct with the specified name and an unsafe trait of the same name plus the suffix Variant. For example

This example is not tested
pub(crate) union MyUnion<'a, T: 'a>: Debug+'a where T: Debug+Copy = &'a str | Option<T>

generates

This example is not tested
pub(crate) struct MyUnion<'a, T: 'a> where T: Debug+Copy {
    /* ... */
}

pub(crate) unsafe trait MyUnionVariant<'a, T: 'a>: Debug+'a where T: Debug+Copy { }

The trait will automatically be implemented for all specified variants. The struct has a single associated method:

This example is not tested
pub(crate) fn new(value: impl MyUnionVariant<'a, T>) -> Self { /* ... */ }

The struct implements Deref and DerefMut with Target = Debug+'a.