strum
strum copied to clipboard
Provide derive macro for creating const &'static strs
IntoStaticStr cannot be used inside const functions. It would be nice if there were a derive macro for this that could be used with const. For example:
use std::borrow::Cow;
use strum_macros::AsStaticStr;
#[derive(AsStaticStr)]
pub enum Thing {
Foo,
Bar
}
pub const FOO: &'static str = Thing::Foo.as_static_str();
// Or inside a const function which is more useful
pub struct ThingString(Cow<'static, str>);
impl ThingString {
pub const fn new(thing: Thing) -> Self {
Self(Cow::Borrowed(thing.as_static_str()))
}
}
pub const FOO_STRING: ThingString = ThingString::new(Thing::FOO);
I am struggling with limitation this in a similar scenario:
trait Jwt {
const AUDIENCE: &'static str;
}
impl Jwt for () {
const AUDIENCE: &'static str = Audience::Access.into();
}
#[derive(Debug, IntoStaticStr)]
enum Audience {
Access,
}
fn main() {
dbg!(JWT::AUDIENCE);
}
Fails with:
error[E0015]: calls in constants are limited to constant functions, tuple structs and tuple variants
--> src/main.rs:6:36
|
6 | const AUDIENCE: &'static str = Audience::Access.into();
| ^^^^^^^^^^^^^^^^^^^^^^^
Having a const function for creating a &'static str for the variant would be useful here for easier re-use of existing constants.
Playground: link