#variant-name #name #enums #variant #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

#2664 in Rust patterns

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