#name #determine #macro #string #bindings #const

nameof

Provides a Rust macro to determine the string name of a binding, type, const, or function

9 releases (stable)

Uses old Rust 2015

1.2.2 Oct 31, 2021
1.2.1 Aug 17, 2020
1.2.0 Feb 10, 2020
1.1.0 May 29, 2019
0.1.1 Jan 4, 2018

#339 in Rust patterns

Download history 437/week @ 2023-12-16 329/week @ 2023-12-23 205/week @ 2023-12-30 471/week @ 2024-01-06 482/week @ 2024-01-13 312/week @ 2024-01-20 362/week @ 2024-01-27 297/week @ 2024-02-03 273/week @ 2024-02-10 358/week @ 2024-02-17 406/week @ 2024-02-24 485/week @ 2024-03-02 451/week @ 2024-03-09 589/week @ 2024-03-16 345/week @ 2024-03-23 347/week @ 2024-03-30

1,800 downloads per month
Used in 11 crates (9 directly)

MIT license

11KB
115 lines

nameof

Crate Version Build Status MIT License

The name_of!() macro defined in this crate 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 stringify!().

Usage

Add nameof as a dependency to your project's Cargo.toml file:

[dependencies]
nameof = "1.2.2"

To use the macro(s), import the crate with the required annotation:

use nameof::name_of;

fn main() {
    let text = "Hello, World!";
    println!("Binding `{}` holds `{}`.", name_of!(text), text);
}

Examples

The name_of!() macro is used as follows:

use nameof::name_of;

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"
}

fn main() {
    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)
    );
}

Alternatively, name_of_type!(T) can be used instead of name_of!(type T).

use nameof::name_of_type;

struct TestStruct {
    test_field: i32,
}

fn main() {
    println!("Struct is called `{}`.", name_of_type!(TestStruct));
    println!("Type is called `{}`.", name_of_type!(i32));
}

License

See LICENSE.txt.

No runtime deps