variants-struct
A derive macro to convert enums into a struct where the variants are members.
Effectively, its like using a HashMap<MyEnum, MyData>
, but it generates a hard-coded struct instead
of a HashMap to reduce overhead.
Basic Example
Applying the macro to a basic enum (i.e. one without tuple variants or struct variants) like this:
use VariantsStruct;
would produce the following code:
The members can be accessed either directly (like hello.world
) or by using the getter methods, like:
let mut hello = new;
*hello.get_mut_unchecked = 5;
assert_eq!;
assert_eq!;
The getters can be particularly useful with the enum-iterator crate. For basic enums,
the checked-getters will always return Some(...)
, so using get_unchecked
is recommended, but this is not the case when the enum contains tuple variants.
Keep in mind that the enum variants are renamed from CamelCase to snake_case, to be consistent with Rust's naming conventions.
Visibility
The struct fields are always pub
, and the struct shares the same visibility as the enum.
Customizing the struct
Renaming
By default, the struct's name is <OriginalEnumName>Struct
. You can set it to something else with the struct_name
attribute. For example, this:
will produce a struct with name SomeOtherName
.
You can also rename the individual fields manually with the field_name
attribute. For example, this:
Will produce the following struct:
Derives
By default no derives are applied to the generated struct. You can add derive macro invocations with the struct_derive
attribute. For example, this:
use ;
would produce the following code:
// impl block omitted
Trait Bounds
By default the struct's type argument T
has no trait bounds, but you can add them with the struct_bounds
attribute. For example, this:
would produce the following code:
Combinations
Note that many derives don't require that the type argument T
fulfills any trait bounds. For example, applying the Clone
derive to the struct only makes the struct cloneable if T
is cloneable, and still allows un-cloneable types to be used with the struct.
So if you want the struct to always be cloneable, you have to use both the derive and the trait bound:
These two attributes, and the struct_name
attribute, can be used in any order, or even multiple times (although that wouldn't be very readable).
Tuple and Struct Variants
Tuple variants are turned into a HashMap
, where the data stored in the tuple is the key (so the data must implement Hash
).
Unfortunately, variants with more than one field in them are not supported.
Tuple variants are omitted from the struct's new
function. For example, this:
produces the following code:
Notice that the new
function now only takes the world
argument, and the unchecked getter methods query the hashmap and unwrap the result.
The same can also be done in struct variants that have only one field.
License: MIT OR Apache-2.0