rust-lang-nursery / lazy-static.rs

A small macro for defining lazy evaluated static variables in Rust.
Apache License 2.0
1.9k stars 111 forks source link

How to use the `vis` specifier inside the `lazy_static!` macro? #146

Open magiclen opened 5 years ago

magiclen commented 5 years ago

When compiling the code below

#[macro_use]
extern crate lazy_static;

macro_rules! unit_like_struct {
    ( $v:vis $name:ident) => {
        $v struct $name;
    }
}

unit_like_struct!(pub MyStruct);

macro_rules! lazy_string {
    ( $v:vis $name:ident, $s:expr) => {
        lazy_static! {
            $v static ref $name: String = format!($s);
        }
    }
}

lazy_string!(pub NOTHING, "nothing");

Cargo says,

error: no rules expected the token `pub `
  --> src/main.rs:15:13
   |
15 |             $v static ref $name: String = format!($s);
   |             ^^ no rules expected this token in macro call
...
20 | lazy_string!(pub NOTHING, "nothing");
   | ------------------------------------- in this macro invocation

Thanks in advance!

KodrAus commented 5 years ago

Hi @magiclen :wave:

Unfortunately the lazy_static macro predates proper macro support for pub(restricted) (which appears to have stabilized in 1.30.0) so it rolls its own. This doesn't appear to be compatible with the proper vis matcher. That's a bit nasty though, so we should look at shifting to vis at some point.