Skip to content

Prefer T::from over .try_into().unwrap() in error messages #73145

Closed
@leonardo-m

Description

@leonardo-m

This wrong code:

fn foo(x: u8, y: u32) -> bool {
    x > y
}
fn main() {}

Currently gives:

error[E0308]: mismatched types
 --> ...\test.rs:2:9
  |
2 |     x > y
  |         ^ expected `u8`, found `u32`
  |
help: you can convert an `u32` to `u8` and panic if the converted value wouldn't fit
  |
2 |     x > y.try_into().unwrap()
  |         ^^^^^^^^^^^^^^^^^^^^^

But rust could give a little smarter error message:

error[E0308]: mismatched types
 --> ...\test.rs:2:5
  |
2 |     x > y
  |     ^ expected `u32`, found `u8`
  |
help: you can convert an `u8` to `u32`: `u32::from(x)`
  |
2 |     u32::from(x) > y
  |     ^^^^^^^^^^^^

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`C-enhancementCategory: An issue proposing an enhancement or a PR with one.D-papercutDiagnostics: An error or lint that needs small tweaks.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