我在一些地方看到了 assert_eq!(a, b, )
,但是我不太确定如何通过代码区分它和 assert_eq!(a, b)
。有人能否解释一下这两者之间是否有区别?
我在一些地方看到了 assert_eq!(a, b, )
,但是我不太确定如何通过代码区分它和 assert_eq!(a, b)
。有人能否解释一下这两者之间是否有区别?
Rust允许在很多地方使用尾逗号,在大多数内置宏中也遵循这个规则。这两个assert_eq!
调用之间没有区别。同样,我们可以像这样声明一个结构体:
struct Example {
foo: i32,
bar: i32, // Note: trailing comma on this line
}
通常,如果调用只有一行,则末尾逗号不会起到任何有用的作用。所以我认为这很奇怪,但完全有效。
assert_eq!(a, b, )
另一方面,如果这两个表达式足够复杂,以至于独占一行,这有助于Git的区别和可读性。我认为以下方式非常符合惯用语。
assert_eq!(
some_complicated_expression(arg1, arg2, arg3),
some_complicated_expression(argA, argB, argC),
)
这两者没有区别。你可以查看 源代码 来了解逗号是可选的:
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);
}
}
}
});
另请参阅:
assert_eq!
可以接受额外的可选参数,用来指定一个用户友好的错误信息。 - Silvio Mayolo