Skip to content

Associated type in higher-rank trait bounds cause unexpected E0227 and useless help #94160

Closed
@Toru3

Description

@Toru3

Given the following code: code in playground

use std::ops::Add;

fn add<T>(a: T, b: T) -> T
where
    T: for<'x> From<<&'x T as Add>::Output>,
    for<'x> &'x T: Add,
{
    T::from(&a + &b)
}

fn main() {
    add(1i32, 2i32); // E0227 with useless help
    //add::<i32>(1i32, 2i32); // works
}

The current output is:

error[E0277]: the trait bound `for<'x> i32: From<<&'x i32 as Add>::Output>` is not satisfied
  --> src/main.rs:12:5
   |
12 |     add(1i32, 2i32); // E0227 with useless help
   |     ^^^ the trait `for<'x> From<<&'x i32 as Add>::Output>` is not implemented for `i32`
   |
note: required by a bound in `add`
  --> src/main.rs:5:8
   |
3  | fn add<T>(a: T, b: T) -> T
   |    --- required by a bound in this
4  | where
5  |     T: for<'x> From<<&'x T as Add>::Output>,
   |        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `add`
help: consider introducing a `where` bound, but there might be an alternative better way to express this requirement
   |
11 | fn main() where i32: for<'x> From<<&'x i32 as Add>::Output> {
   |           +++++++++++++++++++++++++++++++++++++++++++++++++

For more information about this error, try `rustc --explain E0277`.
error: could not compile `playground` due to previous error

Ideally the help should look like:

help: consider introducing the explicit type `::<i32>`
   |
12 |     add::<i32>(1i32, 2i32); // E0227 with useless help
   |        +++++++

Not higher-rank trait bounds (below code) is compiled successfully.

use std::ops::Add;

fn add<T>(a: T, b: T) -> T
where
    T: From<<T as Add>::Output> + Add,
{
    T::from(a + b)
}

fn main() {
    add(1i32, 2i32); // works
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsT-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