Reputation: 1071
I saw assert_eq!(a, b, )
in a few places and I am not very comfortable with macros to tell the difference from assert_eq!(a, b)
by looking at the code. Can someone explain if there is a difference between the two?
Upvotes: 3
Views: 551
Reputation: 431699
There is no difference between the two. You can look at the source code to see that the comma is optional:
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);
}
}
}
});
See also:
Upvotes: 1
Reputation: 70357
Rust allows trailing commas in a lot of places, and most built-in macros respect this convention as well. There's no difference between the two assert_eq!
calls. Similarly, we can declare a struct like this
struct Example {
foo: i32,
bar: i32, // Note: trailing comma on this line
}
Generally, the trailing comma does nothing useful if the call is a single line. So I would find this weird, but perfectly valid
assert_eq!(a, b, )
On the other hand, if the two expressions are complex enough to be on their own line, it helps with git diffs and readability. I find the following very idiomatic
assert_eq!(
some_complicated_expression(arg1, arg2, arg3),
some_complicated_expression(argA, argB, argC),
)
Upvotes: 8