#enums #variant #conversion #newtype #automatic #macro #generate

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

#422 in Rust patterns

Download history 3679/week @ 2024-06-08 3479/week @ 2024-06-15 1875/week @ 2024-06-22 2444/week @ 2024-06-29 2494/week @ 2024-07-06 2210/week @ 2024-07-13 3191/week @ 2024-07-20 4816/week @ 2024-07-27 3455/week @ 2024-08-03 3843/week @ 2024-08-10 3645/week @ 2024-08-17 4018/week @ 2024-08-24 3984/week @ 2024-08-31 4043/week @ 2024-09-07 3027/week @ 2024-09-14 2995/week @ 2024-09-21

15,040 downloads per month
Used in 37 crates (7 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

~2MB
~43K SLoC