Skip to content

Box::new recommended in struct initialization identifier position #139631

Closed
@ginnyTheCat

Description

@ginnyTheCat

Code

struct X {
    a: Box<u32>,
}

fn main() {
    let a = 8;
    let x = X { a };
}

Current output

error[E0308]: mismatched types
 --> src/main.rs:7:17
  |
7 |     let x = X { a };
  |                 ^ expected `Box<u32>`, found integer
  |
  = note: expected struct `Box<u32>`
               found type `{integer}`
  = 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
help: store this in the heap by calling `Box::new`
  |
7 |     let x = X { Box::new(a) };
  |                  ++++++++ +

For more information about this error, try `rustc --explain E0308`.
error: could not compile `tmp` (bin "tmp") due to 1 previous error

Desired output

error[E0308]: mismatched types
 --> src/main.rs:7:17
  |
7 |     let x = X { a };
  |                 ^ expected `Box<u32>`, found integer
  |
  = note: expected struct `Box<u32>`
               found type `{integer}`
  = 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
help: store this in the heap by calling `Box::new`
  |
7 |     let x = X { a: Box::new(a) };
  |                  +++++++++++++

For more information about this error, try `rustc --explain E0308`.
error: could not compile `tmp` (bin "tmp") due to 1 previous error

Rationale and extra context

I'm not quite sure whether this is desired this way but following the recommendation and putting X { Box::new(a) } in the code doesn't suggest adding the a, that's why I thought reporting this may be useful.

Other cases

Rust Version

rustc 1.88.0-nightly (934880f58 2025-04-09)
binary: rustc
commit-hash: 934880f586f6ac1f952c7090e2a943fcd7775e7b
commit-date: 2025-04-09
host: x86_64-unknown-linux-gnu
release: 1.88.0-nightly
LLVM version: 20.1.2

Anything else?

No response

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsD-invalid-suggestionDiagnostics: A structured suggestion resulting in incorrect code.D-papercutDiagnostics: An error or lint that needs small tweaks.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