Easily convert your types into the corresponding enum variant.
Commonly in Rust, you'll have enum variants with a single field – such enums let you differentiate between different types of values. For example, you might have a hierarchy of possible app messages:
```rust, ignore use into_variant::VariantFrom;
enum AppMessage { File(FileMessage), Editor(EditorMessage), }
enum FileMessage { Save(SaveMessage), Close(CloseMessage), }
enum EditorMessage { Insert(InsertMessage), Formatting(FormattingMessage), }
struct SaveMessage {} struct CloseMessage {} struct InsertMessage {} ```
Normally, if you wanted to construct one of these messages, you'd have to type a long chain of nested enums:
rust, ignore
AppMessage::File(FileMessage::Save(SaveMessage {}))
// ^^^^^^^^^^^^^^^^^^^^^^^^ this bit is redundant, let's infer it automatically!
However, since there is only one way to create an AppMessage
with a SaveMessage
inside, we can infer the enum variants automatically – that's what this crate is for!
```rust, ignore
fn testvariantfrom() { assert!(matches!( AppMessage::variant_from(SaveMessage {}), AppMessage::File(FileMessage::Save(SaveMessage {})) ));
assert!(matches!(
AppMessage::variant_from(InsertMessage {}),
AppMessage::Editor(EditorMessage::Insert(InsertMessage {}))
));
} ```
You also get into_variant
, which gets even shorter if AppMessage
can be inferred too – for example, in function calls:
```rust, ignore
fn testintovariant() { functionthattakesappmessage(SaveMessage {}.into_variant()) }
fn functionthattakesappmessage(_message: AppMessage) {} ```
Works for arbitrarily deeply nested enums!
```rust, ignore
enum FormattingMessage { ClearFormatting(ClearFormattingMessage), }
struct ClearFormattingMessage {}
fn testdeepernesting() { assert!(matches!( AppMessage::variant_from(ClearFormattingMessage {}), AppMessage::Editor(EditorMessage::Formatting( FormattingMessage::ClearFormatting(ClearFormattingMessage {}) )) )) } ```
You can find the full example, along with others, in tests/app_message.rs
.
I needed this for a thing, so it might get maintained for a while. Suggestions are appreciated, but I can't guarantee I'll address them.