#newtype #enums #macro

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

#186 in Rust patterns

Download history 5658/week @ 2025-12-09 4974/week @ 2025-12-16 2904/week @ 2025-12-23 3074/week @ 2025-12-30 5418/week @ 2026-01-06 5660/week @ 2026-01-13 6779/week @ 2026-01-20 5794/week @ 2026-01-27 7005/week @ 2026-02-03 6883/week @ 2026-02-10 15887/week @ 2026-02-17 12489/week @ 2026-02-24 12447/week @ 2026-03-03 17207/week @ 2026-03-10 18500/week @ 2026-03-17 18905/week @ 2026-03-24

70,142 downloads per month
Used in 65 crates (15 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