Wishlist: compiler should give hint when trying to use Box<Trait> as Trait

b651e04
Opened by Jeremy Fitzhardinge at 2024-12-21 05:09:58

If I have a function:

fn foo<F: Foo>(f: F) { ... }

and I pass it Box<Foo>, this fails because Box<Foo> doesn't actually implement the Foo trait. Ideally it should, but as a stop-gap the compiler should hint at that problem, because it wasn't obvious to me that a boxed trait object doesn't implement that trait.

  1. Perhaps this would be better as a clippy lint.

    Clar Fon at 2017-06-01 18:36:33

  2. Well, its going to be reporting an error anyway; I'm just suggesting that it explicitly call out that that Box<Trait> doesn't implement Trait.

    I haven't used clippy much, because it's still unstable only (right?) - but I assume it points out issues on code which is correct enough to compile, but are not necessarily ideal stylistically.

    Jeremy Fitzhardinge at 2017-06-01 18:39:42

  3. Triage: Current output:

    error[E0277]: the trait bound `std::boxed::Box<dyn Foo>: Foo` is not satisfied
      --> src/main.rs:11:5
       |
    11 |     foo(x);
       |     ^^^ the trait `Foo` is not implemented for `std::boxed::Box<dyn Foo>`
       |
    note: required by `foo`
      --> src/main.rs:1:1
       |
    1  | fn foo<F: Foo>(f: F) { panic!() }
       | ^^^^^^^^^^^^^^^^^^^^
    

    Update:

    error[E0277]: the trait bound `std::boxed::Box<dyn Foo>: Foo` is not satisfied
      --> src/main.rs:11:9
       |
    1  | fn foo<F: Foo>(f: F) { panic!() }
       |    ---    --- required by this bound in `foo`
    ...
    11 |     foo(x);
       |         ^ the trait `Foo` is not implemented for `std::boxed::Box<dyn Foo>`
    

    Update:

    error[E0277]: the trait bound `Box<dyn Foo>: Foo` is not satisfied
      --> src/main.rs:11:9
       |
    11 |     foo(x);
       |     --- ^ the trait `Foo` is not implemented for `Box<dyn Foo>`
       |     |
       |     required by a bound introduced by this call
       |
       = help: the trait `Foo` is implemented for `Bar`
    note: required by a bound in `foo`
      --> src/main.rs:1:11
       |
    1  | fn foo<F: Foo>(f: F) { panic!() }
       |           ^^^ required by this bound in `foo`
    

    Esteban Kuber at 2019-09-03 00:56:12