【问题标题】:Understanding the dbg! macro in Rust [closed]了解dbg! Rust 中的宏 [关闭]
【发布时间】: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)),+,)
    };
}

这段代码有几件事让我感到困惑:

  1. $ 运算符在这段代码中的作用是什么?
  2. ($val:expr $(,)?) 对应的平面语言是什么?我不明白, 是什么以及为什么会出现。
  3. 为什么宏定义以() => {$crate::eprintln!("[{}:{}]", $crate::file!(), $crate::line!());};开头?

【问题讨论】:

  • 3.使用它作为 dbg!() 不带任何参数将输出源文件中的当前位置。

标签: rust


【解决方案1】:

贯穿这段代码的 $ 运算符是做什么的?

macro_rules! 在普通 Rust 之上具有不同的语法。 $s 用于表示元变量(如$ident)和重复(如$(...))。您可能应该对 Rust 宏是什么做一些初步研究:


($val:expr $(,)?) 对应的平面语言是什么?我不明白, 是什么以及为什么会出现。

$val:expr 定义了一个匹配单个表达式的模式。 $(,)? 匹配可能存在零次或一次的,。有效地使 dbg! 允许可选的尾随逗号(以模仿大部分 Rust)。您会在另一个模式$($val:expr),+ $(,)? 中看到这一点。


为什么宏定义以() => {$crate::eprintln!("[{}:{}]", $crate::file!(), $crate::line!());};开头?

这个宏被设计成可以用任意数量的参数调用,包括零。 () => { ... }; 模式允许 dbg!() 有效。不带参数调用dbg! 的效果是只记录文件和行号。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-31
    • 2023-03-06
    • 2021-08-21
    • 2016-03-15
    • 1970-01-01
    相关资源
    最近更新 更多