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);
答案 0 :(得分:2)
如果只需要进行调试,则可以使编译器打印如下类型的错误消息:
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`
或者,以@DenysSé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);
}