Skip to content

Improve error message for attempt to statically allocate trait object #57186

Closed
@gabcbrown

Description

@gabcbrown

Simple example:

trait T {}

struct S;

impl T for S {}

fn foo<X: T>(s: X) -> X {
    s
}

fn main() {
    let x: T = foo(S);
}

This gives the error message:

error[E0277]: the size for values of type `dyn T` cannot be known at compilation time
  --> src/main.rs:12:9
   |
12 |     let x: T = foo(S);
   |         ^ doesn't have a size known at compile-time
   |
   = help: the trait `std::marker::Sized` is not implemented for `dyn T`
   = 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: all local variables must have a statically known size
   = help: unsized locals are gated as an unstable feature

The following code works, so perhaps it would be useful for the compiler error to suggest using Box:

trait T {}

struct S;

impl T for S {}

fn foo<X: T>(s: X) -> Box<X> {
    Box::new(s)
}

fn main() {
    let x: Box<T> = foo(S);
}

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`C-enhancementCategory: An issue proposing an enhancement or a PR with one.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