Skip to content

Trait resolution fails with unclear error when using function types as input parameters #62385

@gnzlbg

Description

@gnzlbg

This works (Playground):

trait Call<F> {
    type Ret;
    fn call(self, f: F) -> Self::Ret;
}

impl Call<f32> for f32 {
    type Ret = f32;
    fn call(self, f: f32) -> Self::Ret {
        f
    }
}
impl Call<i32> for f32 {
    type Ret = i32;
    fn call(self, f: i32) -> Self::Ret {
        f
    }
}

fn main() {
    let _ = (0_f32).call(0_i32);
}

but this fails (Playground):

trait Call<F> {
    type Ret;
    fn call(self, f: F) -> Self::Ret;
}

impl Call<fn(f32) -> f32> for f32 {
    type Ret = f32;
    fn call(self, f: fn(f32) -> f32) -> Self::Ret {
        f(self)
    }
}
impl Call<fn(f32) -> i32> for f32 {
    type Ret = i32;
    fn call(self, f: fn(f32) -> i32) -> Self::Ret {
        f(self)
    }
}

fn main() {
    fn u0(x: f32) -> f32 {
        x
    }
    let _ = (0_f32).call(u0);
}

with

error[E0277]: the trait bound `f32: Call<fn(f32) -> f32 {main::u0}>` is not satisfied
  --> src/main.rs:23:21
   |
23 |     let _ = (0_f32).call(u0);
   |                     ^^^^ the trait `Call<fn(f32) -> f32 {main::u0}>` is not implemented for `f32`
   |
   = help: the following implementations were found:
             <f32 as Call<fn(f32) -> f32>>
             <f32 as Call<fn(f32) -> i32>>

error: aborting due to previous error

I'm not sure if this is by design or not (AFAICT the trait bound is satisfied - EDIT: it is by design, see below), but the error message could be at least much clearer.

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`A-trait-systemArea: Trait systemC-enhancementCategory: An issue proposing an enhancement or a PR with one.D-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions