我想创建一个类似于标准dbg的自定义宏!macro,但可以选择通过彩色板条箱使用颜色。dbg!通常以以下格式打印一些东西
[path_to_file:line_number] "symbol name" = "symbol value"
//[src/gallery/image_slot.rs:231] "my_integer_value_of_12" = "12"
Run Code Online (Sandbox Code Playgroud)
[path_to_file:line_number]以便打印?my_var给出my_var = 12)file!,line!和column!宏。stringify!宏。如果你去dbg!宏的文档,你可以点击[src],它显示了 的实现dbg!,如下所示:
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)),+,)
};
}
Run Code Online (Sandbox Code Playgroud)
使用它,我们可以轻松创建一个类似的colored_dbg!宏,使用您建议的colored板条箱。
(我只是选择了随机颜色,举个简单的例子)
// colored = "2.0"
use colored::Colorize;
macro_rules! colored_dbg {
() => {
eprintln!("{}", format!("[{}:{}]", file!(), line!()).green());
};
($val:expr $(,)?) => {
match $val {
tmp => {
eprintln!("{} {} = {}",
format!("[{}:{}]", file!(), line!()).green(),
stringify!($val).red(),
format!("{:#?}", &tmp).blue(),
);
tmp
}
}
};
($($val:expr),+ $(,)?) => {
($(colored_dbg!($val)),+,)
};
}
Run Code Online (Sandbox Code Playgroud)
您可以像使用它一样使用它dbg!:
// colored = "2.0"
use colored::Colorize;
macro_rules! colored_dbg {
() => {
eprintln!("{}", format!("[{}:{}]", file!(), line!()).green());
};
($val:expr $(,)?) => {
match $val {
tmp => {
eprintln!("{} {} = {}",
format!("[{}:{}]", file!(), line!()).green(),
stringify!($val).red(),
format!("{:#?}", &tmp).blue(),
);
tmp
}
}
};
($($val:expr),+ $(,)?) => {
($(colored_dbg!($val)),+,)
};
}
Run Code Online (Sandbox Code Playgroud)
输出以下内容: