strum

Derive Macro AsRefStr

Source
#[derive(AsRefStr)]
{
    // Attributes available to this derive:
    #[strum]
}
Expand description

Converts enum variants to &'a str, where 'a is the lifetime of the input enum reference.

Implements AsRef<str> on your enum using the same rules as Display for determining what string is returned. The difference is that as_ref() returns a &str instead of a String so you don’t allocate any additional memory with each call.

If you require a &'static str, you can use strum::IntoStaticStr instead.

// You need to bring the AsRef trait into scope to use it
use std::convert::AsRef;
use strum_macros::AsRefStr;

#[derive(AsRefStr, Debug)]
enum Color {
    #[strum(serialize = "redred")]
    Red,
    Green {
        range: usize,
    },
    Blue(usize),
    Yellow,
}

// uses the serialize string for Display
let red = Color::Red;
assert_eq!("redred", red.as_ref());
// by default the variants Name
let yellow = Color::Yellow;
assert_eq!("Yellow", yellow.as_ref());
// or for string formatting
println!(
    "blue: {} green: {}",
    Color::Blue(10).as_ref(),
    Color::Green { range: 42 }.as_ref()
);

// With prefix on all variants
#[derive(AsRefStr, Debug)]
#[strum(prefix = "/")]
enum ColorWithPrefix {
    #[strum(serialize = "redred")]
    Red,
    Green,
}

assert_eq!("/redred", ColorWithPrefix::Red.as_ref());
assert_eq!("/Green", ColorWithPrefix::Green.as_ref());