#macro #variant #deref #as-variant

no-std as_variant

A simple macro to convert enums with newtype variants to Options

5 stable releases

1.3.0 Mar 26, 2025
1.2.0 Aug 9, 2023
1.1.0 Sep 14, 2022
1.0.1 Sep 13, 2022

#179 in Rust patterns

Download history 3232/week @ 2025-01-10 3451/week @ 2025-01-17 3341/week @ 2025-01-24 4570/week @ 2025-01-31 4524/week @ 2025-02-07 3762/week @ 2025-02-14 4104/week @ 2025-02-21 3602/week @ 2025-02-28 4214/week @ 2025-03-07 4311/week @ 2025-03-14 3454/week @ 2025-03-21 4255/week @ 2025-03-28 3644/week @ 2025-04-04 3757/week @ 2025-04-11 3711/week @ 2025-04-18 3288/week @ 2025-04-25

14,827 downloads per month
Used in 40 crates (11 directly)

MPL-2.0 license

9KB

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)
    }
}

No runtime deps