Expand description
This crate provides a macro that generates a trait-union type. That is, a trait object type which can contain any one of a pre-determined set of implementors.
The generated type does not allocate. The size of the type is the size of the largest variant plus some constant overhead.
NOTE: As of rustc 1.47, you must enable the untagged_unions
feature to store
non-Copy types in a trait-union. This will change
soon.
§Example
trait_union! {
/// Container can contain either an i32, a &'static str, or a bool.
union Container: Display = i32 | &'static str | bool;
}
let mut container = Container::new(32);
assert_eq!(container.to_string(), "32");
container = Container::new("Hello World");
assert_eq!(container.to_string(), "Hello World");
container = Container::new(true);
assert_eq!(container.to_string(), "true");
The generated type has the following interface:
ⓘ
struct Container {
/* ... */
}
impl Container {
fn new(value: impl ContainerVariant) -> Self { /* ... */ }
}
impl Deref for Container {
type Target = dyn Display + 'static;
/* ... */
}
impl DerefMut for Container {
/* ... */
}
unsafe trait ContainerVariant: Display + 'static { }
unsafe impl ContainerVariant for i32 { }
unsafe impl ContainerVariant for &'static str { }
unsafe impl ContainerVariant for bool { }
Macros§
- trait_
union - Macro that generates a trait-union type
- trait_
union_ copy - Macro that generates a trait-union type for Copy implementors