Crates.io | trait-union |
lib.rs | trait-union |
version | 0.1.4 |
source | src |
created_at | 2020-10-10 20:07:00.488567 |
updated_at | 2020-10-12 10:01:08.085568 |
description | Stack-allocated trait objects |
homepage | |
repository | https://github.com/mahkoh/trait-union |
max_upload_size | |
id | 298157 |
size | 27,863 |
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.
use trait_union::trait_union;
use std::fmt::Display;
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 looks roughly as follows:
struct Container {
data: union {
variant1: i32,
variant2: &'static str,
variant3: bool,
},
vtable: *mut (),
}
Its size is therefore similar to the size of an enum
with one variant per implementor.
Depending on the number of implementors, compile times should be significantly lower than
with an enum
. The run-time performance is similar to that of Box<dyn Trait>
.
This project is licensed under either of
at your option.