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

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

#107 in No standard library

Download history 1706/week @ 2024-10-30 1710/week @ 2024-11-06 2473/week @ 2024-11-13 2753/week @ 2024-11-20 2823/week @ 2024-11-27 2906/week @ 2024-12-04 3157/week @ 2024-12-11 2559/week @ 2024-12-18 1317/week @ 2024-12-25 2478/week @ 2025-01-01 3127/week @ 2025-01-08 3655/week @ 2025-01-15 3271/week @ 2025-01-22 3960/week @ 2025-01-29 4883/week @ 2025-02-05 3060/week @ 2025-02-12

15,933 downloads per month
Used in 38 crates (11 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