Description
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.
Activity
jyn514 commentedon Jun 1, 2021
This would be nice to suggest for all traits with derives in the standard library, and maybe with derives from third-party crates too if the crate is in your dependency tree (like
thiserror
andError
, orFrom
andderive_more
).inquisitivecrystal commentedon Jun 5, 2021
@rustbot label C-enhancement D-newcomer-roadblock
ptrojahn commentedon Jun 25, 2021
@rustbot claim
Suggest deriving traits if possible
Auto merge of rust-lang#86943 - ptrojahn:suggest_derive, r=estebank
1 remaining item