#macro #variant #deref

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

#166 in Rust patterns

Download history 4414/week @ 2025-02-01 4396/week @ 2025-02-08 4086/week @ 2025-02-15 3837/week @ 2025-02-22 3794/week @ 2025-03-01 3999/week @ 2025-03-08 4256/week @ 2025-03-15 3688/week @ 2025-03-22 3949/week @ 2025-03-29 3905/week @ 2025-04-05 3417/week @ 2025-04-12 3996/week @ 2025-04-19 3395/week @ 2025-04-26 3886/week @ 2025-05-03 3764/week @ 2025-05-10 2760/week @ 2025-05-17

14,429 downloads per month
Used in 43 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