#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

#52 in No standard library

Download history 852/week @ 2023-12-13 838/week @ 2023-12-20 916/week @ 2023-12-27 1194/week @ 2024-01-03 956/week @ 2024-01-10 1186/week @ 2024-01-17 1300/week @ 2024-01-24 1243/week @ 2024-01-31 1470/week @ 2024-02-07 1195/week @ 2024-02-14 1418/week @ 2024-02-21 1718/week @ 2024-02-28 1513/week @ 2024-03-06 1653/week @ 2024-03-13 1834/week @ 2024-03-20 1248/week @ 2024-03-27

6,567 downloads per month
Used in 29 crates (7 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