rust - 如何通过宏获取声明的变量名和变量类型

标签 rust macros

macro_rules! print_entity {
    ($x: expr) => {
        {
            println!("Object type: {}\nDeclared name: {}\n")
        }
    }
}

对于定义的引用,考虑:

let the_foo: MyBar = MyBar::new();

在上述宏的情况下,“声明的名称”值应等于 the_foo。结构类型应等于 TheBar。如何做到这一点?

print_entity!(the_foo);

最佳答案

如果你只需要它来调试,你可以让编译器打印一条错误消息,类型如下:

let foo: () = 1i32;

出现以下错误:

error[E0308]: mismatched types
  --> src/main.rs:24:15
   |
24 | let foo: () = 1i32;
   |               ^^^^ expected (), found i32
   |
   = note: expected type `()`
              found type `i32`

或者,根据@Denys Séguret 的评论,您需要定义一个特征并为您可能想要打印的每种类型实现它(这也可以通过宏变得更容易):

trait TypeToStr {
    fn get_type_str (&self) -> &'static str;
}

macro_rules! impl_type_to_str {
    ($($T: ty),+) => {
        $(
        impl TypeToStr for $T {
            fn get_type_str (&self) -> &'static str { stringify!($T) }
        }
        )*
    }
}

impl_type_to_str!(i32, f64);

macro_rules! print_type {
    ($e: expr) => {
        println!("{} has type {}", stringify!($e), $e.get_type_str());
    }
}

fn main() {
    print_type!(1i32);
    print_type!(3.14f64);
}

playground

关于rust - 如何通过宏获取声明的变量名和变量类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57067811/

相关文章:

c - 为什么宏后面的分号会导致非法的else编译错误

scala - 宏返回类型和高阶函数

c - 在宏定义中转义结构字段

c - 在#define 子句中,如何让预处理器替换变量名中的参数?

asynchronous - 如何将 Future 转换为 Stream?

image - Rust 打开文件扩展名以外格式的图像

rust - 由于类型不匹配错误,文本文件解析函数无法编译

rust - 如何使用堆分配的数据创建常量枚举变体以用于模式匹配?

rust - 使用 Piston 有效绘制路径

macros - Lisp宏的基本思想