Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Provide derive macro for creating const &'static strs #152

Open
liamcurry opened this issue Mar 3, 2021 · 1 comment
Open

Provide derive macro for creating const &'static strs #152

liamcurry opened this issue Mar 3, 2021 · 1 comment

Comments

@liamcurry
Copy link

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);
@seanpianka
Copy link

seanpianka commented Oct 20, 2021

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants