#enums #variant #try-from #macro

enum_variant_macros

Macros to generate From & TryFrom for enums

3 releases (breaking)

0.3.0 Apr 8, 2023
0.2.0 May 30, 2022
0.1.0 Feb 23, 2022

#2338 in Rust patterns

Download history 1/week @ 2024-03-16 1/week @ 2024-03-23 69/week @ 2024-03-30 44/week @ 2024-04-06 4/week @ 2024-04-13 22/week @ 2024-04-20 7/week @ 2024-04-27 73/week @ 2024-05-11 6/week @ 2024-05-18 139/week @ 2024-05-25 55/week @ 2024-06-01 57/week @ 2024-06-08 15/week @ 2024-06-15 39/week @ 2024-06-22 2/week @ 2024-06-29

116 downloads per month
Used in xcodeproj

MIT/Apache

10KB
50 lines

Enum Variant Macros

Macro library for use in generating From & TryFrom implementations for enums composed of unnamed single members. In other terms, of the following format.

pub enum Variants {
    Integer(i32),
    Float(f32),
    Bool(bool),
    Byte(u8),
}

This library has 2 macros, TryFromVariants & FromVariants.

TryFromVariants implements TryFrom for each of the variant types, permitting code such as,

use enum_variant_macros::*;
use std::error::Error;
use strum_macros::IntoStaticStr;

#[derive(IntoStaticStr, TryFromVariants)]
enum Variants {
    Integer(i32),
    Float(f32),
}

fn main() -> Result<(), Box<dyn Error>> {
    let variant = Variants::Float(12.0);
    let float: f32 = TryFrom::try_from(variant)?;
    Ok(())
}

Note: Derivation of this type also requires that impl From<Variant> for &'static str is implemented.

FromVariants is relatively simple, it just generates From for each wrapped type.

use enum_variant_macros::*;

#[derive(Debug, PartialEq, FromVariants)]
enum Variants {
    Integer(i32),
    Float(f32),
}

let variant = Variants::from(12);
assert_eq!(Variants::Integer(12), variant);

Note

If this library is not to your preference, may I recomend enum dispatch, a more expansive library that also provides from & try_into for enums.

License

Licensed under either of Apache License, Version 2.0 or MIT license at your option.

Dependencies

~300–760KB
~18K SLoC