3

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?

savx2
  • 1,011
  • 2
  • 10
  • 28

2 Answers2

8

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),
)
Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
  • quick question on the git diff improvement especially in the assert_eq! macro. Does it allow multiple arguments because otherwise how would it improve the git diff ? – khalilw1 May 10 '21 at 17:38
  • 1
    [`assert_eq!`](https://doc.rust-lang.org/std/macro.assert_eq.html) can take additional optional arguments to specify a user-friendly error message. – Silvio Mayolo May 10 '21 at 17:39
1

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:

Timmmm
  • 88,195
  • 71
  • 364
  • 509
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366