rust-lang / rust-lang/rust

Struct update syntax doesn't reborrow mut references

Open
#126,411 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-bug C-discussion T-lang
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

When using struct update syntax to copy a struct's &mut fields, the compiler will complain about the field being moved, even though it could logically be reborrowed.

Here's a minimal example:

struct Foobar<'a> {
    s: &'a str,
}

// Works fine
fn take_foobar(foobar: Foobar<'_>) {
    let foobar2 = Foobar {
        ..foobar
    };
    dbg!(foobar.s);
}

struct FoobarMut<'a> {
    s: &'a mut str,
}

// COMPILE ERROR - error[E0382]: use of moved value: `foobar.s`
fn take_foobar_mut(foobar: FoobarMut<'_>) {
    let foobar2 = FoobarMut {
        ..foobar
    };
    dbg!(foobar.s);
}

(Playground link)

I'm not familiar with compiler internals, but from a very rough guess, this doesn't seem like a use-case that would need architectural changes to handle. If we replace the use of struct update syntax with copying the individual fields, the code works fine:

fn take_foobar_mut_2(foobar: FoobarMut<'_>) {
    let foobar2 = FoobarMut {
        s: foobar.s
    };
    dbg!(foobar.s);
}
Meta
rustc 1.78.0 (9b00956e5 2024-04-29)
binary: rustc
commit-hash: 9b00956e56009bab2aa15d7bff10916599e3d6d6
commit-date: 2024-04-29
host: x86_64-unknown-linux-gnu
release: 1.78.0
LLVM version: 18.1.2

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 minimal Rust examples with rustc 1.78.0 or the linked Playground, comparing struct update syntax with explicit field initialization. Trace the rustc entry point for struct updates and borrow/move checking; done means the FoobarMut example compiles without E0382.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.