Macro static_sym

Source
macro_rules! static_sym {
    ($sym:ident) => { ... };
    ($sym:literal) => { ... };
    (@impl $sym:expr) => { ... };
}
Expand description

Create a static location for a literal symbol.

This macro works the same as sym!(...), except that it produces a StaticSymbol instead of a Symbol. StaticSymbol implements Deref<Target = Symbol>, so it can be used in most places where a Symbol is expected.

This macro also requires the presence of a call to the enable!() macro at the crate root.

This macro can be used in the initialization of a static or const variable:

static MY_SYMBOL: StaticSymbol = static_sym!("Hello, World!");
const OTHER_SYMBOL: StaticSymbol = static_sym!(abc);

assert_eq!(MY_SYMBOL, sym!("Hello, World!"));
assert_eq!(OTHER_SYMBOL, sym("abc"));

§Use case

Use this macro to avoid having too many “magic symbols” in your code (similar to “magic numbers”). Declare common symbol names centrally, and refer to them by their Rust names instead.

At runtime, using symbols declared as static_sym!(...) is actually very slightly less efficient than using sym!(...) directly, due to a necessary extra indirection. This is probably negligible in almost all cases, but it is counterintuitive nevertheless. (This caveat may be lifted in future, but is due to a - potentially overzealous - check in the compiler which requires the indirection.)

§Low-level details

Another (extremely niche) effect of using this macro over sym!(...) is that it can help reduce the link-time size of the symbol table. Each sym!(...) and static_sym!(...) call site adds 8 bytes to the .bss segment, so this can only matter when you have in the order of millions of symbols in your binary. Still, worth knowing if you are golfing binary size.