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