【问题标题】:Is there a difference between `assert_eq!(a, b)` and `assert_eq!(a, b, )`?`assert_eq!(a, b)` 和 `assert_eq!(a, b, )` 之间有区别吗?
【发布时间】:2021-05-10 17:33:48
【问题描述】:

我在几个地方看到了assert_eq!(a, b, ),我不太习惯通过查看代码来区分与assert_eq!(a, b) 的宏。谁能解释一下两者之间是否有区别?

【问题讨论】:

    标签: rust


    【解决方案1】:

    Rust 允许在很多地方使用尾随逗号,并且大多数内置宏也遵守此约定。两个assert_eq! 调用之间没有区别。同样,我们可以像这样声明一个结构体

    struct Example {
      foo: i32,
      bar: i32, // Note: trailing comma on this line
    }
    

    通常,如果调用是单行,则结尾的逗号没有任何用处。所以我会觉得这很奇怪,但完全有效

    assert_eq!(a, b, )
    

    另一方面,如果这两个表达式足够复杂,可以单独一行,它有助于 git diffs 和可读性。我发现以下非常地道

    assert_eq!(
      some_complicated_expression(arg1, arg2, arg3),
      some_complicated_expression(argA, argB, argC),
    )
    

    【讨论】:

    • 关于 git diff 改进的快速问题,尤其是在 assert_eq 中!宏。它是否允许多个参数,否则它将如何改进 git diff ?
    • assert_eq! 可以采用其他可选参数来指定用户友好的错误消息。
    【解决方案2】:

    两者没有区别。你可以查看at the source code 看逗号是可选的:

    macro_rules! assert_eq {
        ($left:expr, $right:expr $(,)?) => ({
            match (&$left, &$right) {
                (left_val, right_val) => {
                    if !(*left_val == *right_val) {
                        let kind = $crate::panicking::AssertKind::Eq;
                        // The reborrows below are intentional. Without them, the stack slot for the
                        // borrow is initialized even before the values are compared, leading to a
                        // noticeable slow down.
                        $crate::panicking::assert_failed(kind, &*left_val, &*right_val, $crate::option::Option::None);
                    }
                }
            }
        });
    

    另见:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-04
      • 2012-06-26
      • 1970-01-01
      • 2017-12-24
      • 1970-01-01
      • 1970-01-01
      • 2019-12-18
      • 2016-01-13
      相关资源
      最近更新 更多