Skip to content

Error messages can be ambiguous between types and type parameters #81971

Open
@leo60228

Description

@leo60228

Someone I know was learning Rust as a beginner. They defined a function like this:

fn test<T>(t: T) -> i32 {
    5_i32 + <i32 as From<T>>::from(t)
}

This resulted in an error:

error[E0277]: the trait bound `i32: From<T>` is not satisfied
 --> src/lib.rs:2:13
  |
2 |     5_i32 + <i32 as From<T>>::from(t)
  |             ^^^^^^^^^^^^^^^^^^^^^^ the trait `From<T>` is not implemented for `i32`
  |
  = note: required by `from`

Based on this error, they attempted to add an i32: From<T> bound:

fn test<T, i32: From<T>>(t: T) -> i32 {
    5_i32 + <i32 as From<T>>::from(t)
}

This leads to a different, very misleading error:

error[E0277]: cannot add `i32` to `i32`
 --> src/lib.rs:2:11
  |
2 |     5_i32 + <i32 as From<T>>::from(t)
  |           ^ no implementation for `i32 + i32`
  |
  = help: the trait `Add<i32>` is not implemented for `i32`

#[warn(non_camel_case_types)] can give a hint, but I think that the error message should stand on its own. In addition, they appear to have added #![allow(non_camel_case_types)] for unrelated reasons.

Meta

rustc --version --verbose: (N/A, on playground)

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-bugCategory: This is a bug.D-confusingDiagnostics: Confusing error or lint that should be reworked.D-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.D-terseDiagnostics: An error or lint that doesn't give enough information about the problem at hand.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