#macro #enums #variant #convert #newtype #options

no-std as_variant

A simple macro to convert enums with newtype variants to Options

4 stable releases

1.2.0 Aug 9, 2023
1.1.0 Sep 14, 2022
1.0.1 Sep 13, 2022

#41 in No standard library

Download history 1638/week @ 2024-04-08 1851/week @ 2024-04-15 2514/week @ 2024-04-22 2046/week @ 2024-04-29 2059/week @ 2024-05-06 1845/week @ 2024-05-13 1983/week @ 2024-05-20 1733/week @ 2024-05-27 1924/week @ 2024-06-03 1828/week @ 2024-06-10 2215/week @ 2024-06-17 1898/week @ 2024-06-24 2061/week @ 2024-07-01 1854/week @ 2024-07-08 2111/week @ 2024-07-15 2192/week @ 2024-07-22

8,387 downloads per month
Used in 31 crates (9 directly)

MPL-2.0 license

8KB

as_variant

docs.rs

A simple Rust macro to convert enums with newtype variants to Options.

Basic example:

use std::ops::Deref;

use as_variant::as_variant;

enum Value {
    Integer(i64),
    String(String),
    Array(Vec<Value>),
}

impl Value {
    pub fn as_integer(&self) -> Option<i64> {
        as_variant!(self, Self::Integer).copied()
    }

    pub fn as_str(&self) -> Option<&str> {
        as_variant!(self, Self::String).map(Deref::deref)
    }

    pub fn as_array(&self) -> Option<&[Value]> {
        as_variant!(self, Self::Array).map(Deref::deref)
    }

    pub fn into_string(self) -> Option<String> {
        as_variant!(self, Self::String)
    }

    pub fn into_array(self) -> Option<Vec<Value>> {
        as_variant!(self, Self::Array)
    }
}

lib.rs:

Provides a simple macro to convert enums with newtype variants to Options.

No runtime deps