enum_convert
Crate to derive From implementations between enums.
Features
- EnumFrom: Derive
From<Source> for AnnotatedEnum - EnumInto: Derive
From<AnnotatedEnum> for Target - Support for multiple source/target enums
- Flexible variant name mapping (one-to-many, many-to-one)
- Field-level mapping for named struct variants
- Automatic type conversion for fields via
.into()
Usage
EnumFrom - Convert from source enums to annotated target enum
use EnumFrom;
// Usage
let source = Tuple;
let target: Target = source.into;
EnumInto - Convert from annotated source enum to target enums
ℹ️ While the macro is named EnumInto, it still implements From<AnnotatedEnum> for TargetEnum and thus has an indirect implementation of Into as recommended by the docs.
This is similar to derive_more's Into.
use EnumInto;
// Usage
let source = Variant;
let target: Target = source.into;
Advanced Features
Multiple source/target enums
use EnumFrom;
Field mapping
use EnumFrom;
Related and similar crates
derive_more
This crate has some similarities with derive_more's From and Into derive macros.
The difference is that with derive_more the conversion is field → variant (From) and variant → field (Into); with this crate it is variant ↔ variant.
// `derive_more::From` get expanded to
// `enum_convert::EnumFrom` get expanded to
enum_to_enum
This crate is very similar to enum_to_enum.
At the time of writing (enum_to_enum in version 0.1.0) the differences are:
enum_convertdoes not support many-to-one conversion with try_into logic .enum_convertdoes not support effectful conversion.enum_to_enumdoes not supportEnumInto.enum_to_enumdoes not support having variants in the target for which there is no mapping from source.enum_to_enumdoes not support fields mapping.
For the common features, here is a comparison of how they are expressed in both crates:
subenum
The subenum crate allows to implement easily subset of enums with conversion between parent and child.
However, there are cases where it is not desirable or possible to use subenum.
For example:
- You don't want to declare the child enum in the same module or crate as the parent enum.
- There already is a child enum coming from another crate and you want to convert from that child enum to your own parent enum.