Skip to content

Misleading Error Message: the trait Foo is not implemented for &dyn Foo #73492

@ObliqueMotion

Description

@ObliqueMotion

Here is a minimal example [playground]:

pub trait Foo {
    fn bar(&self, _: &dyn Foo) -> bool {
        true
    }
}

impl Foo for u32 {}

fn main() {
    let x = 1;
    let v: Vec<&dyn Foo> = vec![&1, &2, &3];
    v.iter().all(|y| x.bar(y));
}

Which produces this error:

error[E0277]: the trait bound `&dyn Foo: Foo` is not satisfied
  --> src/main.rs:14:28
   |
14 |     v.iter().all(|y| x.bar(y));
   |                            ^ the trait `Foo` is not implemented for `&dyn Foo`
   |
   = note: required for the cast to the object type `dyn Foo`

I find this error to be misleading because:

  1. The type of y within the closure should be &&dyn Foo, not &dyn Foo.
  2. Even though the type listed in the error message seems wrong, the trait Foo should be implemented for &dyn Foo if that were the actual type of y.

This can be fixed in a number of ways:

v.iter().all(|&y| x.bar(y));
v.iter().all(|&y| x.bar(&*y));
v.iter().all(|y| x.bar(*y));
v.iter().all(|y| x.bar(&**y));
v.into_iter().all(|y| x.bar(y));

All of which are consistent with y being of type &&dyn Foo, and none of which are suggested by the error message.

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`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