Skip to content

Accept extra parameters in assert_eq!, pass them to panic! #1604

@SimonSapin

Description

@SimonSapin

The assert! macro has a one-argument form that simply takes a boolean expression, and a "detailed" form where extra arguments are passed to panic!, allowing the user to change the panic message.

The assert_eq! macro however only has one form: two arguments that are compared for equality.

https://twitter.com/natpryce/status/656110689082286080?s=09

@ rustlang's assert_eq macro doesn't take a msg param, so I pass it tuples of values & context to get good diagnostics. What do others do?

I propose adding another form form assert_eq! where additional arguments are passed to panic!. But unlike assert!, I think this should add to the default message instead of replacing it. Something like:

macro_rules! assert_eq {
    ($left:expr , $right:expr) => ({
        match (&($left), &($right)) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    panic!("assertion failed: `(left == right)` \
                           (left: `{:?}`, right: `{:?}`)", left_val, right_val)
                }
            }
        }
    });
    ($left:expr , $right:expr, $fmt:expr, $($arg:tt)*) => ({
        match (&($left), &($right)) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    panic!(concat!("assertion failed: `(left == right)` \
                                   (left: `{:?}`, right: `{:?}`) ", $fmt),
                           left_val, right_val, $($arg)*)
                }
            }
        }
    });
}

CC @alexcrichton

Metadata

Metadata

Assignees

No one assigned

    Labels

    T-libs-apiRelevant to the library API team, which will review and decide on the RFC.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions