rust-lang / rust-lang/rust

inconsistent and confusing error message about first argument of `assert!`

Open
#122,159 1 comment 0 reactions 1 assignee View on GitHub

@estebank is already working on this.

Since Mar 17, 2024.

A-diagnostics D-confusing T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

Code
fn f(x: Result<i8, Box<dyn std::error::Error>>) {
    assert!(x.unwrap(), "expected Ok");      // expected `bool`, found `i8`
    assert!(x.unwrap_err(), "expected Err"); // cannot apply unary operator `!`
}
Current output
error[E0308]: mismatched types
 --> src/lib.rs:2:5
  |
2 |     assert!(x.unwrap(), "expected Ok");      // expected `bool`, found `i8`
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `bool`, found `i8`

error[E0600]: cannot apply unary operator `!` to type `Box<dyn std::error::Error>`
 --> src/lib.rs:3:5
  |
3 |     assert!(x.unwrap_err(), "expected Err"); // cannot apply unary operator `!` to type `Box<dyn std::error::Error>`
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot apply unary operator `!`
  |
  = note: this error originates in the macro `assert` (in Nightly builds, run with -Z macro-backtrace for more info)

Some errors have detailed explanations: E0308, E0600.
For more information about an error, try `rustc --explain E0308`.
Desired output

No response

Rationale and extra context

The macro assert! is documented as taking a bool as its first parameter. Therefore I suggest the error message be expected `bool`, found `i8` in both cases.

The very different error messages are very confusing, because Result::unwrap and Result::unwrap_err are basically the same. While I understand both error messages, I do not understand why they are different.

Edit: I just realized it's probably because i8 has an implementation of std::ops::Not. Still weird.

Other cases

No response

Rust Version
rustc 1.76.0 (07dca489a 2024-02-04)
binary: rustc
commit-hash: 07dca489ac2d933c78d3c5158e3f43beefeb02ce
commit-date: 2024-02-04
host: x86_64-unknown-linux-gnu
release: 1.76.0
LLVM version: 17.0.6
Anything else?

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.