Skip to content

Suggest reordering fields for a borrow of a moved value #150320

@Patryk27

Description

@Patryk27

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsT-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