#enums #variant #conversions #newtype #automatically #macro #generating

from_variants

Rust macro to automatically generate conversions for newtype enums

15 releases (3 stable)

1.0.2 Feb 8, 2023
1.0.0 Feb 24, 2022
0.6.0 Mar 3, 2021
0.5.0 Jul 21, 2020
0.2.3 Jun 19, 2017

#172 in Rust patterns

Download history 4633/week @ 2023-11-18 3831/week @ 2023-11-25 3754/week @ 2023-12-02 2368/week @ 2023-12-09 4692/week @ 2023-12-16 2328/week @ 2023-12-23 3180/week @ 2023-12-30 3204/week @ 2024-01-06 5084/week @ 2024-01-13 4292/week @ 2024-01-20 2714/week @ 2024-01-27 2294/week @ 2024-02-03 3540/week @ 2024-02-10 3443/week @ 2024-02-17 4226/week @ 2024-02-24 2841/week @ 2024-03-02

14,548 downloads per month
Used in 33 crates (9 directly)

MIT/Apache

6KB

Build Status Latest Version

Newtype Variant Conversions

Rust macro crate to automatically generate conversions from variant types into the target enum.

This crate requires Rust 1.45 or above to compile on stable.

Examples

use from_variants::FromVariants;

#[derive(Debug, Clone, PartialEq, Eq, FromVariants)]
pub enum Lorem {
    Str(String),
    Num(u16),
}

fn main() {
    assert_eq!(Lorem::Num(10), Lorem::from(10));
}

You can skip variants to avoid type collisions:

use from_variants::FromVariants;

#[derive(Debug, Clone, PartialEq, Eq, FromVariants)]
pub enum Ipsum {
    Hello(String),

    #[from_variants(skip)]
    Goodbye(String),
}

fn main() {
    assert_eq!(Ipsum::Hello("John".to_string()), Ipsum::from("John".to_string()));
}

Features

  • Variant opt-out: To skip a variant, add #[from_variants(skip)] to that variant.
  • Conversion opt-in: Use #[from_variants(into)] on an enum or variant to generate conversions that will automatically convert - for example, accepting a &str for a String variant. This must be used sparingly to avoid generating conflicting impls.
  • no_std support: Generated conversions do not depend on the standard library.

Dependencies

~1.5MB
~40K SLoC