Skip to content

Spurious 'help: store this in the heap' on error involving &Box<dyn SomeTrait> #82446

Closed
@Aaron1011

Description

@Aaron1011

The following code:

trait MyTrait {}

struct Foo {
    val: Box<dyn MyTrait>
}

fn make_it(val: &Box<dyn MyTrait>) {
    Foo {
        val
    };
}

produces the following error:

error[E0308]: mismatched types
 --> src/lib.rs:9:9
  |
9 |         val
  |         ^^^
  |         |
  |         expected struct `Box`, found reference
  |         help: store this in the heap by calling `Box::new`: `Box::new(val)`
  |
  = note: expected struct `Box<(dyn MyTrait + 'static)>`
          found reference `&Box<(dyn MyTrait + 'static)>`
  = note: for more on the distinction between the stack and the heap, read https://doc.rust-lang.org/book/ch15-01-box.html, https://doc.rust-lang.org/rust-by-example/std/box.html, and https://doc.rust-lang.org/std/boxed/index.html

error: aborting due to previous error

val is a &Box<dyn MyTrait>, so writing Box::new(val) would produce a Box<&Box<dyn MyTrait>>. This is very unlikely to be what the user wants - and in this case, it won't even work, since there are no impls for MyTrait.

Meta

Tested on rustc 1.52.0-nightly 2021-02-22

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsC-bugCategory: This is a bug.D-incorrectDiagnostics: A diagnostic that is giving misleading or incorrect information.D-invalid-suggestionDiagnostics: A structured suggestion resulting in incorrect code.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