Macro nameof::name_of[][src]

macro_rules! name_of {
    ($n : ident) => { ... };
    (type $t : ty) => { ... };
    ($n : ident in $t : ty) => { ... };
    (const $n : ident in $t : ty) => { ... };
}
Expand description

Takes a binding, type, const, or function as an argument and returns its unqualified string representation. If the identifier does not exist in the current context, the macro will cause a compilation error. This macro is mainly intended for debugging purposes and to improve the refactoring experience compared to plain stringify!().

The syntax depends on the type of the identifier:

  1. Bindings to variables and functions require no annotation, e.g. name_of!(some_binding).

  2. Types and structs require the keyword type, e.g. name_of!(type SomeType). Alternatively, the macro name_of_type!(SomeType) may be used.

  3. Fields within structs are referred to with the in keyword, e.g. name_of!(some_field in SomeType).

Examples

struct TestStruct {
    test_field: i32,
}

impl TestStruct {
    const TEST_CONST: i32 = 1;
}

struct GenericStruct<T> {
    test_field_t: T,
}

fn greet() -> &'static str {
    "Hi, World"
}

let text = "Hello, World!";

println!("Binding `{}` holds `{}`.", name_of!(text), text);

println!("Function `{}` says `{}`.", name_of!(greet), greet());

println!(
    "Struct `{}` has a field `{}`.",
    name_of!(type TestStruct),
    name_of!(test_field in TestStruct)
);

println!(
    "Generic Struct `{}` has a field `{}`.",
    name_of!(type GenericStruct<String>),
    name_of!(test_field_t in GenericStruct<String>)
);

println!(
    "Struct `{}` has an associated constant `{}`.",
    name_of!(type TestStruct),
    name_of!(const TEST_CONST in TestStruct)
);

println!(
    "Standard types such as `{}` and `{}` also work.",
    name_of!(type i32),
    name_of!(type f64)
);