trait_union!() { /* proc-macro */ }Expand description
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:
/// 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:
Debug+Copy+'a // OK
'a // Error: No trait
Debug+Display // Error: More than one non-auto traitIf you do not provide a lifetime, the 'static lifetime will be added automatically.
That is, Debug is the same as Debug+'static. For example
union MyUnion<'a>: Debug = &'a str;will not compile because &'a str is not 'static. Write
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
pub(crate) union MyUnion<'a, T: 'a>: Debug+'a where T: Debug+Copy = &'a str | Option<T>generates
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:
pub(crate) fn new(value: impl MyUnionVariant<'a, T>) -> Self { /* ... */ }The struct implements Deref and DerefMut with Target = Debug+'a.