derive_more
derive_more copied to clipboard
custom `AsStr` trait
trafficstars
i'd like to propose a derive for static string "as_str" methods for enums. for example:
trait AsStr {
fn as_str(&self) -> &'static str;
}
#[derive(AsStr)]
enum Foo {
A, // Foo::A.as_str() -> "A"
#[as_str(rename = "lowercase")]
B, // Foo::B.as_str() -> "b"
#[as_str(transparent)]
C(Bar), // Foo::C(Bar::D).as_str() -> "ddd"
}
#[derive(AsStr)]
enum Bar {
#[as_str("ddd")]
D,
E,
}
i think this is nicer as a trait because i like namespaces, but 🤷♀
i'd also like the derive macro to have a few attrs, like:
renamesimilar to #216, which can be on a container or varianttransparentwhich transparently returns the inner field'sas_strmethod- a raw string to specify the static string returned by the variant
i think it makes sense to only allow deriving on enums, any other container likely has labeled data. likewise, i think this derive should only allow unit tuple variants or variants marked with as_str(transparent)
this is particularly interesting as an alternative to Display, which allocates.