rust-lang / rust-lang/rust

Suggest reordering fields for a borrow of a moved value

Open
#150,320 1 comment 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

A-diagnostics T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

Code
struct Foo {
    a: String,
    b: usize,
}

impl Foo {
    fn new(a: String) -> Self {
        Self {
            a,
            b: a.len(),
        }
    }
}
Current output
error[E0382]: borrow of moved value: `a`
  --> src/lib.rs:10:16
   |
 7 |     fn new(a: String) -> Self {
   |            - move occurs because `a` has type `String`, which does not implement the `Copy` trait
 8 |         Self {
 9 |             a,
   |             - value moved here
10 |             b: a.len(),
   |                ^ value borrowed here after move
   |
help: consider cloning the value if the performance cost is acceptable
   |
 9 |             a: a.clone(),
   |              +++++++++++
Desired output
error[E0382]: borrow of moved value: `a`
  --> src/lib.rs:10:16
   |
 7 |     fn new(a: String) -> Self {
   |            - move occurs because `a` has type `String`, which does not implement the `Copy` trait
 8 |         Self {
 9 |             a,
   |             - value moved here
10 |             b: a.len(),
   |                ^ value borrowed here after move
   |
help: consider initializing `b` before `a`
   |
 9 |             b: a.len(),
   |             ++++++++++++
10 |             a,
   |             ++
   |
help: otherwise consider cloning the value if the performance cost is acceptable
   |
 9 |             a: a.clone(),
   |              +++++++++++
Rationale and extra context

No response

Other cases

Rust Version
1.94.0-nightly 2025-12-22
Anything else?

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the E0382 diagnostic with the Rust example in the issue and inspect the compiler's handling of this borrow-after-move case. Done means the diagnostic suggests initializing b before a while retaining the existing cloning suggestion, with coverage for the shown example and relevant other cases.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.