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

nameof

提供 Rust 宏,用于确定绑定、类型、常量或函数的字符串名称

9 个版本 (稳定)

使用旧的 Rust 2015

1.2.2 2021 年 10 月 31 日
1.2.1 2020 年 8 月 17 日
1.2.0 2020 年 2 月 10 日
1.1.0 2019 年 5 月 29 日
0.1.1 2018 年 1 月 4 日

#346Rust 模式

Download history 546/week @ 2024-03-14 416/week @ 2024-03-21 332/week @ 2024-03-28 291/week @ 2024-04-04 346/week @ 2024-04-11 235/week @ 2024-04-18 436/week @ 2024-04-25 414/week @ 2024-05-02 378/week @ 2024-05-09 358/week @ 2024-05-16 325/week @ 2024-05-23 424/week @ 2024-05-30 301/week @ 2024-06-06 343/week @ 2024-06-13 347/week @ 2024-06-20 204/week @ 2024-06-27

1,238 每月下载量
11 个crate(9 个直接)中使用

MIT 许可证

11KB
115

nameof

Crate Version Build Status MIT License

此crate中定义的 name_of!() 宏接受绑定、类型、常量或函数作为参数,并返回其无限定字符串表示。如果标识符在当前上下文中不存在,则此宏将导致编译错误。此宏主要用于调试目的,并与 stringify!() 相比,以提高重构体验。

用法

nameof 添加到项目的 Cargo.toml 文件中作为依赖项

[dependencies]
nameof = "1.2.2"

要使用宏,请导入具有所需注解的crate

use nameof::name_of;

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

示例

name_of!() 宏的使用如下

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)
    );
}

或者,可以使用 name_of_type!(T) 代替 name_of!(类型 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.txt

无运行时依赖