macro_vis

Attribute Macro macro_vis

Source
#[macro_vis]
Expand description

Attribute that applies a visibility to a macro_rules! macro.

By default, placing #[macro_vis] on a macro causes it to have a private visibility like functions, structs and enums do by default. In comparison to regular macro_rules! macros, this means two things:

  • It can be used before it is declared.
  • It can’t be used in submodules declared after the macro without importing it first.
// Use before declaration:
private_macro!();

#[macro_vis]
macro_rules! private_macro { () => {}; }

mod inner {
    // Doesn't work like with a regular macro, because it's not in scope:
    // private_macro!();
    // Does work:
    super::private_macro!();
    // or:
    crate::private_macro!();
    // You can also `use crate::private_macro;` just like any other item.
}

You can also supply a custom visibility to #[macro_vis]. For example, to make a macro visible anywhere within the current crate:

inner::example_macro!();

// No `#[macro_use]` needed!
mod inner {
    #[macro_vis(pub(crate))]
    macro_rules! example_macro { () => {}; }
}

Public macros will be exported at the current module path instead of at the crate root as with #[macro_export]:

pub mod inner {
    #[macro_vis(pub)]
    macro_rules! public_macro { () => {}; }
}

// Doesn't work like with a `#[macro_export]`ed macro:
// crate::public_macro!();

// Does work:
crate::inner::public_macro!();