Crates.io | enum_stringify |
lib.rs | enum_stringify |
version | |
source | src |
created_at | 2023-09-13 11:03:00.028246 |
updated_at | 2024-12-02 21:04:04.234356 |
description | Macro to generate string conversion functions for enums |
homepage | https://github.com/Yag000/enum_stringify |
repository | https://github.com/Yag000/enum_stringify |
max_upload_size | |
id | 971388 |
Cargo.toml error: | TOML parse error at line 18, column 1 | 18 | autolib = false | ^^^^^^^ unknown field `autolib`, expected one of `name`, `version`, `edition`, `authors`, `description`, `readme`, `license`, `repository`, `homepage`, `documentation`, `build`, `resolver`, `links`, `default-run`, `default_dash_run`, `rust-version`, `rust_dash_version`, `rust_version`, `license-file`, `license_dash_file`, `license_file`, `licenseFile`, `license_capital_file`, `forced-target`, `forced_dash_target`, `autobins`, `autotests`, `autoexamples`, `autobenches`, `publish`, `metadata`, `keywords`, `categories`, `exclude`, `include` |
size | 0 |
Set of macros (only one for now) to generate a string representation of an enum. When using
#[derive(EnumStringify)]
on an enum, it will implement std::fmt::Display
, TryFrom<&str>
,
TryFrom<String>
and std::str::FromStr
for it. It will use the name of the enum variant as the
string representation.
use enum_stringify::EnumStringify;
#[derive(EnumStringify)]
enum MyEnum {
Variant1,
Variant2,
Variant3,
}
fn main() {
println!("{}", MyEnum::Variant1); // Prints "Variant1"
assert_eq!(MyEnum::Variant1.to_string(), "Variant1");
assert_eq!(MyEnum::try_from("Variant2").unwrap(), MyEnum::Variant2);
assert_eq!(MyEnum::try_from("Variant3".to_string()).unwrap(), MyEnum::Variant3);
assert_eq!(MyEnum::from_str("Variant1").unwrap(), MyEnum::Variant1);
}
You can customize the string representation of the enum by adding prefixes or/and suffixes to the variants and also changing the case of the string representation.
use enum_stringify::EnumStringify;
#[derive(EnumStringify)]
#[enum_stringify(prefix = "MyPrefix", suffix = "MySuffix", case = "upper_flat")]
enum MyEnum {
Variant1,
Variant2,
Variant3,
}
In this case the string representation of MyEnum::Variant1
will be MyPrefixVariant1MySuffix
(and
so on for the other variants).
See docs.rs for documentation. It is available on crates.io as well.