Why does &dyn Trait not implement Trait?

Maybe I’m misunderstanding the way that references to dyn Trait are intended to be used, but why does the following:

trait Foo {}
impl Foo for () {}

fn needs_foo<T>(x: T) where T: Foo {}

fn main() {
    let my_foo: &dyn Foo = &();
    needs_foo(my_foo);
}

fail to compile with:

error[E0277]: the trait bound `&dyn Foo: Foo` is not satisfied
 --> src/main.rs:8:5
  |
8 |     needs_foo(my_foo);
  |     ^^^^^^^^^ the trait `Foo` is not implemented for `&dyn Foo`
  |
note: required by `needs_foo`
 --> src/main.rs:4:1
  |
4 | fn needs_foo<T>(x: T) where T: Foo {}
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

dyn Trait (unsized type) implements Trait. Implementations for &dyn Trait and/or &mut dyn Trait need to be explicitly provided.

2 Likes

So in other words, what would fix your code would be something like the following:

impl<T: Foo> Foo for &T {}

So that dyn Trait, while under a reference will also impl Foo. Or you could also do

fn needs_foo<T>(x: &T) where T: Foo {}
1 Like

For an example of why this can’t work in general, look no further than the Iterator trait. How would you implement that for &dyn Iterator? (you can’t because next needs a &mut _, which you can’t get from a &_).

5 Likes

This sounds like something the compiler could suggest here, e.g.

note: the trait `Foo` is implemented for `dyn Foo` but not for `&dyn Foo`
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.