enum2str is a rust derive macro that creates a Display impl for enums. This is useful for strongly typing composable sets of strings.
Add this to your Cargo.toml
:
toml
enum2str = "0.1.8"
Example:
```rust use enum2str::EnumStr;
enum Object { Generic(String),
#[enum2str("Color: {}. Shape: {}.")]
Complex(Color, Shape),
// Variant fields can be ignored
#[enum2str("Material")]
Material(Color),
}
enum Color { Green,
#[enum2str("Burgundy")]
Red,
Blue {
_hue: u8,
},
#[enum2str("Custom Color")]
Custom {
_red: u8,
_green: u8,
_blue: u8,
},
#[enum2str("Unique - {label}_{id}")]
Unique {
id: u8,
label: String,
},
}
enum Shape { #[enum2str("Circle with radius: {}")] Circle(u8), }
fn unittostring() { asserteq!(Color::Green.tostring(), "Green"); }
fn unitoverridestring() { asserteq!(Color::Red.tostring(), "Burgundy"); }
fn unnamedtostring() { asserteq!(Object::Generic("Hello!".tostring()).to_string(), "Hello!"); }
fn nestedtostring() { asserteq!( Object::Complex(Color::Green, Shape::Circle(2)).tostring(), "Color: Green. Shape: Circle with radius: 2." ); }
fn unittemplate() { asserteq!(Color::Green.template(), "Green"); }
fn unitoverridetemplate() { assert_eq!(Color::Red.template(), "Burgundy"); }
fn unnamedtemplate() { asserteq!(Shape::Circle(2).template(), "Circle with radius: {}"); }
fn nestedtemplate() { asserteq!( Object::Complex(Color::Green, Shape::Circle(2)).template(), "Color: {}. Shape: {}." ); }
fn unitargs() { asserteq!(Color::Green.arguments().len(), 0); }
fn unnamedargs() { asserteq!( Object::Generic("Hello!".tostring()).arguments(), vec!["Hello!".tostring()] ); }
fn complexargs() { asserteq!( Object::Complex(Color::Green, Shape::Circle(2)).arguments(), vec!["Green", "Circle with radius: 2"], ); }
fn plaintostring() { asserteq!(Color::Blue { _hue: 3 }.tostring(), "Blue"); }
fn uniquetostring() { asserteq!( Color::Unique { label: "uniquecolor".tostring(), id: 3 } .tostring(), "Unique - uniquecolor3", ); }
fn customargs() { asserteq!( Color::Unique { label: "uniquecolor".tostring(), id: 3 } .arguments() .len(), 2 ); } ```