Skip to content

Generate `From<T>` trait from one enum to another enum.

License

Notifications You must be signed in to change notification settings

borngraced/enum-from-variant

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

23 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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.

About

Generate `From<T>` trait from one enum to another enum.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages