Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between `assert_eq!(a, b)` and `assert_eq!(a, b, )`?

Tags:

rust

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?

like image 954
savx2 Avatar asked May 01 '26 04:05

savx2


2 Answers

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),
)
like image 173
Silvio Mayolo Avatar answered May 03 '26 11:05

Silvio Mayolo


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:

  • How to allow optional trailing commas in macros?
like image 40
Shepmaster Avatar answered May 03 '26 10:05

Shepmaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!