#variants #enum #newtype #enums #proc-macro #macro #variant #compile #stable #conversions

from_variants

Rust macro to automatically generate conversions for newtype enums

13 releases (1 stable)

1.0.0 Feb 24, 2022
0.6.0 Mar 3, 2021
0.5.0 Jul 21, 2020
0.4.0 May 14, 2018
0.2.3 Jun 19, 2017

#66 in Rust patterns

Download history 9522/week @ 2022-06-04 6369/week @ 2022-06-11 9002/week @ 2022-06-18 5555/week @ 2022-06-25 7250/week @ 2022-07-02 5728/week @ 2022-07-09 5674/week @ 2022-07-16 3509/week @ 2022-07-23 6451/week @ 2022-07-30 4177/week @ 2022-08-06 6565/week @ 2022-08-13 3855/week @ 2022-08-20 7104/week @ 2022-08-27 5289/week @ 2022-09-03 6201/week @ 2022-09-10 3858/week @ 2022-09-17

23,362 downloads per month
Used in 24 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

~0.5–1MB
~21K SLoC