strum icon indicating copy to clipboard operation
strum copied to clipboard

Provide derive macro for creating const &'static strs

Open liamcurry opened this issue 5 years ago • 1 comments

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);

liamcurry avatar Mar 03 '21 02:03 liamcurry

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

seanpianka avatar Oct 20 '21 06:10 seanpianka