创建自定义彩色 dbg!Rust 中的宏

ANi*_*120 4 rust rust-macros

我想创建一个类似于标准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)
  1. 如何访问路径/行号[path_to_file:line_number]以便打印?
  2. 如何访问变量的符号名称?(即打印my_var给出my_var = 12

Val*_*tin 5

  1. 使用file!line!column!宏。
  2. 使用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)

输出以下内容:

截屏