Skip to content

Incorrect compiler hint on missing stricter trait bound #99597

Closed
@SadiinsoSnowfall

Description

@SadiinsoSnowfall

Let's consider the following snippet:

trait T1 { }

trait T2 {
    fn test(&self) { }
}

fn go(s: &impl T1) {
    s.test();
}

The compiler will throw the following error + hint:

error[[E0599]](https://doc.rust-lang.org/stable/error-index.html#E0599): no method named `test` found for reference `&impl T1` in the current scope
 --> src/lib.rs:8:7
  |
8 |     s.test();
  |       ^^^^ method not found in `&impl T1`
  |
  = help: items from traits can only be used if the type parameter is bounded by the trait
help: the following trait defines an item `test`, perhaps you need to restrict type parameter `impl T1` with it:
  |
7 | fn go(s: &impl T1 + T2) {
  |                   ++++

For more information about this error, try `rustc --explain E0599`.

But the hint is not correct: changing the go function as suggested by the compiler

fn go(s: &impl T1 + T2) {
    s.test();
}

Will result in a new error:

error: ambiguous `+` in a type
 --> src/lib.rs:7:11
  |
7 | fn go(s: &impl T1 + T2) {
  |           ^^^^^^^^^^^^ help: use parentheses to disambiguate: `(impl T1 + T2)`

The compiler hint should be something like this:

help: the following trait defines an item `test`, perhaps you need to restrict type parameter `impl T1` with it:
  |
7 | fn go(s: &(impl T1 + T2)) {
  |           +        +++++

The only case where just adding the restriction works out of the box is when taking an owned value as a parameter:

fn go(s: impl T1 + T2) {
    s.test();
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-trait-systemArea: Trait systemC-bugCategory: This is a bug.D-invalid-suggestionDiagnostics: A structured suggestion resulting in incorrect code.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