#enums #conversion #macro #error-handling #convert #derive-debug #from-trait

macro enum_from_variant

A Rust macro to generate From<T> trait implementations for enum variants, simplifying error conversions and enum mapping

2 releases

0.1.1 Jun 18, 2024
0.1.0 Jun 18, 2024

#2016 in Data structures

MIT license

11KB
144 lines

enum-from-variant crate provides the EnumFromVariant macro, which simplifies the generation of the From trait for converting one enum variant to another enum variant. This is particularly useful when you need to handle error conversions or map different enum types in your Rust code.

USAGE:

Consider the following example where we convert between different enum types using the EnumFromVariant macro:

use enum_from_variant::EnumFromVariant;
use derive_more::Display;

#[derive(Debug, EnumFromVariant)]
pub enum MainError {
    #[enum_from_variant("NetworkError")]
    Network(String),
    #[enum_from_variant("DatabaseError")]
    Database(DatabaseError),
}

#[derive(Debug, Display)]
pub enum NetworkError {
    Timeout(String),
}

#[derive(Debug, Display)]
pub enum DatabaseError {
    ConnectionFailed(String),
}

fn network_request() -> Result<(), MainError> {
    Err(NetworkError::Timeout("Network timeout".to_string()).into())
}

fn main() {
    match network_request() {
        Ok(_) => println!("Request succeeded"),
        Err(e) => println!("Error: {:?}", e),
    }
}

Limitations

Current Support: The macro only supports enum variants with basic inner types like String and other enums. Unsupported Types: Tuple variants, struct variants, and more complex inner types are not supported at this time.

Dependencies

~1.5MB
~36K SLoC