1

In this example, the function foo only accepts a as argument. If changed to accept &dyn Trait, it would only accept b as argument and not a.

trait Trait {}

fn foo<T: Trait>(_: T) {}

fn demo(a: impl Trait, b: &dyn Trait) {
    foo(a);
    foo(b);
}
error[E0277]: the trait bound `&dyn Trait: Trait` is not satisfied
 --> src/lib.rs:7:9
  |
3 | fn foo<T: Trait>(_: T) {}
  |           ----- required by this bound in `foo`
...
7 |     foo(b);
  |         ^ the trait `Trait` is not implemented for `&dyn Trait`

Is there a way such that a function would be able to accept both a and b as an argument?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Garlic Xu
  • 143
  • 1
  • 8
  • 1
    [Applying the duplicate to your situation](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=c4bf0e7d4594e6c82ef2334047bd9091): `impl Trait for &'_ dyn Trait {}` (or the more generic `impl Trait for &'_ T {}`) – Shepmaster Aug 05 '20 at 02:48
  • 1
    @tadman treating a trait object as an implementer of a trait is pretty common. I expect you’ve called a method from `Iterator` on a `Box` – Shepmaster Aug 05 '20 at 03:06

0 Answers0