Creating a Custom Colored dbg! Macro In Rust

隐身守侯 提交于 2021-02-19 03:28:52

问题


I'd like to create a custom macro similar to the standard dbg! macro, but with the option to use colors via the colored crate. dbg! usually prints something with the format of

[path_to_file:line_number] "symbol name" = "symbol value"
//[src/gallery/image_slot.rs:231] "my_integer_value_of_12" = "12"
  1. How do I access the path/line number [path_to_file:line_number] so I can print it?
  2. How do I access the symbol name of a variable? (i.e. print my_var given my_var = 12)

回答1:


  1. Use the file!, line!, and column! macros.
  2. Use the stringify! macro.

If you go to the docs of the dbg! macro, you can click [src], which shows the implementation of dbg!, which is as follows:

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)),+,)
    };
}

Using that, we can easily create a similar colored_dbg! macro, with the colored crate as you suggested.

(I just picked random colors, for a simple example)

// 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)),+,)
    };
}

You'd use it just like how you'd be able to use dbg!:

fn main() {
    let my_var = 12;
    colored_dbg!(&my_var);

    let v = vec!["foo", "bar", "baz"];
    let v = colored_dbg!(v);
}

Which outputs the following:



来源:https://stackoverflow.com/questions/65797610/creating-a-custom-colored-dbg-macro-in-rust

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!