Skip to content

Confusing error message when passing trait object to generic function #57744

Closed
@wesleywiser

Description

@wesleywiser

This could be the same issue as #23286 but I'm not sure.

The following code gives this error (playground):

use std::io::Write;

fn trait_obj(w: &dyn Write) {
    generic(w);
}

fn generic<W: Write>(_w: &W) {
}
error[E0277]: the size for values of type `dyn std::io::Write` cannot be known at compilation time
 --> src/lib.rs:4:5
  |
4 |     generic(w);
  |     ^^^^^^^ doesn't have a size known at compile-time
  |
  = help: the trait `std::marker::Sized` is not implemented for `dyn std::io::Write`
  = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
note: required by `generic`
 --> src/lib.rs:7:1
  |
7 | fn generic<W: Write>(_w: &W) {
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^

error: aborting due to previous error

There's a couple reasons this is very confusing:


4 |     generic(w);
  |     ^^^^^^^ doesn't have a size known at compile-time

points to the function name not the parameter w.


the size for values of type `dyn std::io::Write` cannot be known at compilation time

dyn Write only appears behind a reference which means it should be sized.

We should show a better error message when you pass a &dyn T value to a function expecting a generic &T value.

cc @munik

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 systemD-confusingDiagnostics: Confusing error or lint that should be reworked.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

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions