#variant-name #enums #variant #name #macro

no-std variante

Statically-verified enum variant names as strings

1 unstable release

0.2.0 Dec 29, 2023
0.1.1 Dec 29, 2023
0.1.0 Dec 29, 2023

#1783 in Rust patterns

Download history 36/week @ 2024-02-25 4/week @ 2024-03-10 41/week @ 2024-03-31 69/week @ 2024-04-14

110 downloads per month

MIT/Apache

7KB

variante

Statically verified enum variant names as strings.

This repository is inspired by field.

See the documentation for more details.

Installation

Add the following to your Cargo manifest (Cargo.toml file):

[dependencies]
variante = "0.2.0"

Or, just run cargo add variante.

Dependencies

variante has zero dependencies, and is #[no_std]-compatible by default.

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual-licensed as above, without any additional terms or conditions.


lib.rs:

Statically-verified enum variant names as strings.

The variant! macro evaluates to a variant's name after verifying that the variant exists on the specified enum. The type must be in scope, and the variant must be visible (accessible) at the point of invocation of the macro.

Usage

Invoke the macro as variant!(Variant @ Enum):

use variante::*;

enum Enum {
    Foo,
    Bar(u8),
    Baz { x: i32 },
}

let foo = variant!(Foo @ Enum);
assert_eq!(foo, "Foo");

let bar = variant!(Bar @ Enum);
assert_eq!(bar, "Bar");

let baz = variant!(Baz @ Enum);
assert_eq!(baz, "Baz")

A variant that is not on the specified enum or a type that is not in scope will cause a compilation error:

// This fails because there is no variant named "Hoge" on "Enum"
let hoge = variant!(Hoge @ Enum);

// This fails because their is no enum named "NonExistent"
let foo = variant!(Foo @ NonExistent);

Generics

variant! also works with generic types, as long as concrete type parameters are provided:

use variante::*;

enum GenericEnum<T, U> {
    Foo(T),
    Bar(U),
}

let foo = variant!(Foo @ GenericEnum<(), ()>);
assert_eq!(foo, "Foo");

// Any type can be used for the type parameter(s)
let bar = variant!(Bar @ GenericEnum<i32, i64>);
assert_eq!(bar, "Bar");

Paths

That's right, variant! also works with path syntax:

use variante::*;

mod fuga {
    pub enum Enum<T> {
        Foo(T), // Must be pub so that it is visible at the point of invocation
    }
}

let foo = variant!(Foo @ fuga::Enum<()>);
assert_eq!(foo, "Foo");

Dependencies

This crate is completely dependency-free. #[no_std] is also supported by default.

No runtime deps