Trait enumscribe::TryScribeCowStr
source · pub trait TryScribeCowStr {
// Required method
fn try_scribe(&self) -> Option<Cow<'static, str>>;
}
Expand description
Trait for converting an enum to a clone-on-write string, or None
if the conversion fails.
Like all of the traits provided by enumscribe, this should not be implemented manually; use
#[derive(TryScribeCowStr)]
provided by the
enumscribe_derive crate instead.
When deriving this trait, you may specify the string that a particular variant should be
converted to by annotating it with #[enumscribe(str = "foo")]
. If this is omitted, the name
of the variant will be used instead.
A maximum of one variant can be annotated with #[enumscribe(other)]
. This variant must have
exactly one field, which must implement Into<String>
. Converting this variant to a string
will result in whatever the value of its field is.
You may also annotate a variant with #[enumscribe(ignore)]
, in which case attempting to
convert the variant to a string will always result in None
.
use std::borrow::Cow;
use enumscribe::TryScribeCowStr;
#[derive(TryScribeCowStr, PartialEq, Eq, Debug)]
enum Airport {
#[enumscribe(ignore)]
Heathrow,
#[enumscribe(str = "LGW")]
Gatwick,
#[enumscribe(other)]
Other(String),
}
assert_eq!(Airport::Heathrow.try_scribe(),
None);
assert_eq!(Airport::Gatwick.try_scribe(),
Some(Cow::Borrowed("LGW")));
assert_eq!(Airport::Other("STN".to_owned()).try_scribe(),
Some(Cow::Owned::<'static, str>("STN".to_owned())));
Required Methods§
sourcefn try_scribe(&self) -> Option<Cow<'static, str>>
fn try_scribe(&self) -> Option<Cow<'static, str>>
Converts this enum to a Option<Cow<'static, str>>
.
Calling this method on a variant marked with #[enumscribe(ignore)]
will return None
.
When called on a variant marked with #[enumscribe(other)]
, the variant’s field will be
returned as a Cow::Owned
. For other variants, a Cow::Borrowed
is returned, containing
a static string slice determined by the #[enumscribe(str = "...")]
attribute, or the name
of the variant if the attribute is omitted.