unite

Crates.iounite
lib.rsunite
version0.1.2
sourcesrc
created_at2021-08-11 16:35:24.468703
updated_at2021-08-11 16:35:24.468703
descriptionA helper macro to compose existing types into an enum
homepagehttps://github.com/zerthox/unite
repositoryhttps://github.com/zerthox/unite
max_upload_size
id434858
size12,117
(Zerthox)

documentation

README

Unite

A small helper macro allowing you to compose existing types into an enum.

[dependencies]
unite = "0.1"

Usage

use unite::unite;

pub struct One(bool);
pub struct Two(i32);
pub struct Three(f64);

unite! {
    // defines a new enum with a variant for each struct
    pub enum Any { One, Two, Three }
}

This expands to:

pub enum Any {
    One(One),
    Two(Two),
    Three(Three),
}

Renaming

By default the enum variants use the same name as the type, but renaming is possible.

unite! {
    enum Foo {
        SameName,
        Renamed = i32,
    }
}

Helpers

The generated enums come with helper functions to access their variants with ease. Variant names are automatically converted into snake_case for the function names.

fn foo(any: Any) {
    // checks whether the enum is a specific variant
    let is_one: bool = any.is_one();

    // attempts to cast the enum to a specific variant
    let as_two: Option<&Two> = any.as_two();
    let as_three_mut: Option<&mut Three> = any.as_three_mut();
}

The generated enums also inherently implement From<Variant>.

let any: Any = One(true).into();
Commit count: 10

cargo fmt