【发布时间】:2021-01-28 22:36:16
【问题描述】:
我正在尝试编写一些自己的调试宏,并且正在查看dbg! 中的 rusts 构建源代码:
macro_rules! dbg {
() => {
$crate::eprintln!("[{}:{}]", $crate::file!(), $crate::line!());
};
($val:expr $(,)?) => {
// Use of `match` here is intentional because it affects the lifetimes
// of temporaries - https://stackoverflow.com/a/48732525/1063961
match $val {
tmp => {
$crate::eprintln!("[{}:{}] {} = {:#?}",
$crate::file!(), $crate::line!(), $crate::stringify!($val), &tmp);
tmp
}
}
};
($($val:expr),+ $(,)?) => {
($($crate::dbg!($val)),+,)
};
}
这段代码有几件事让我感到困惑:
-
$运算符在这段代码中的作用是什么? -
($val:expr $(,)?)对应的平面语言是什么?我不明白,是什么以及为什么会出现。 - 为什么宏定义以
() => {$crate::eprintln!("[{}:{}]", $crate::file!(), $crate::line!());};开头?
【问题讨论】:
-
3.使用它作为 dbg!() 不带任何参数将输出源文件中的当前位置。
标签: rust