Skip to content

Suggest missing Debug Impl when unwrapping #85851

Closed
@jamesmunns

Description

@jamesmunns

Hey all, here's another common pitfall our new Rust learners stumble into during our training. The diagnostics you get on unwrap when the E: Debug bound isn't met do tell you that it isn't possible, BUT it doesn't tell you how to fix this. I think in most cases, suggesting #[derive(Debug)] is a better option, though this might give false positives if the user doesn't control the Error type (I don't know if diagnostics can "see" whether a type is local or not, but maybe you can!)

Given the following code: Playground Link

enum MyError {
    Oops,
    No,
    DebugImpl,
}

fn main() {
    let x: Result<(), MyError> = Ok(());
    let y = x.unwrap();
}

The current output is:

error[E0599]: the method `unwrap` exists for enum `Result<(), MyError>`, but its trait bounds were not satisfied
 --> src/main.rs:9:15
  |
1 | enum MyError {
  | ------------ doesn't satisfy `MyError: Debug`
...
9 |     let y = x.unwrap();
  |               ^^^^^^ method cannot be called on `Result<(), MyError>` due to unsatisfied trait bounds
  |
  = note: the following trait bounds were not satisfied:
          `MyError: Debug`

error: aborting due to previous error

I would hope for something that tells users more directly "When you use unwrap(), the Err variant must implement the Debug trait in case the unwrap fails and we need to display a panic message".

error[E0599]: the method `unwrap` exists for enum `Result<(), MyError>`, but its trait bounds were not satisfied
 --> src/main.rs:9:15
  |
1 | enum MyError {
  | ------------ doesn't satisfy `MyError: Debug`
...
9 |     let y = x.unwrap();
  |               ^^^^^^ method cannot be called on `Result<(), MyError>` due to unsatisfied trait bounds
  |
  = note: the following trait bounds were not satisfied:
          `MyError: Debug`
  = help: try implementing the `Debug` trait on `MyError`. When you use `unwrap()`, the `Err(MyError)`
          variant must implement the `Debug` trait in order to display a panic message if the unwrap fails

  | #[derive(Debug)]
  | ^^^^^^^^^^^^^^^^ add a derive Debug here
1 | enum MyError {
  | 

error: aborting due to previous error

Applies to Rust 1.51.1, and likely all other older versions of Rust.

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.D-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions