derive_more icon indicating copy to clipboard operation
derive_more copied to clipboard

custom `AsStr` trait

Open dotcarmen opened this issue 5 months ago • 1 comments
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:

  • rename similar to #216, which can be on a container or variant
  • transparent which transparently returns the inner field's as_str method
  • 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.

dotcarmen avatar May 30 '25 18:05 dotcarmen