#name #macro #string #const #determine #bindings #name-of

ident-util

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

2 个稳定版本

使用旧的 Rust 2015

1.0.1 2022 年 3 月 6 日
1.0.0 2020 年 9 月 24 日

Rust 模式 中排名 1390

MIT 许可证

11KB
125

ident-util

Crate Version MIT License

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

用法

ident-util 添加为项目 Cargo.toml 文件中的依赖项

[dependencies]
ident-util = "1"

要使用宏,请导入带有所需注解的包

#[macro_use]
extern crate ident_util;

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

示例

name_of!() 的使用方法如下

#[macro_use]
extern crate ident_util;

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

    println!("{}", path_of!(crate::greet));
}

或者,可以使用 name_of_type!(T) 替代 name_of!(类型 T)

#[macro_use]
extern crate ident_util;

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

无运行时依赖项