rust-lang / rust-lang/rust

Disjoint capture in async blocks requires mut for Copy field modifications

Open
#146,547 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-async-await C-bug T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

I tried this code:

use std::future::Future;
use std::pin::Pin;
use std::thread::sleep;
use std::time::Duration;

async fn run_multiple_times<Fut>(
    mut f: impl FnMut() -> Pin<Box<dyn Future<Output = Fut> + Send>>,
) {
    for _ in 0..5 {
        f().await;
        sleep(Duration::from_secs(1));
    }
}

struct Test {
    pub num: usize,
    pub name: String,
}

impl Test {
    fn inc(&mut self) {
        self.num += 1
    }
}

#[tokio::main]
async fn main() {
    let mut state = Test {num: 0, name: "test".to_string()};
    run_multiple_times(move || {
        Box::pin(async move {
            println!("State: {}", state.num);

            state.num = state.num + 1; // This line doesn't capture state, yet requires it to be mut ???

            // These two lines, as expected, do not compile:
            // state.inc() // error: cannot move out of `state`
            // state.name = "test".to_string(); // error: String doesn't implement Copy trait
        })
    }).await;
    println!("State: {}", state.num);
}

I expected to see a compilation error due to state being moved twice. Instead, this code compiled without any warnings and printed "State: 0" 6 times. This issue also exists on the nightly version.

The way I understand this is that the compiler decides to move state.num instead of the whole state (which is already confusing) and, since usize implements Copy trait, it simply copies its value. The problem is that the compiler also requires state to be declared as mut which is definitely not how it should be.

Am I missing something or is it an actual bug?

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 compiling the provided minimal reproducer on the stable and nightly Rust versions mentioned in the issue, focusing on the async closure's capture and mutability behavior. Done means determining whether the observed output and required mut binding are intended or represent a compiler bug, then documenting the behavior or implementing the appropriate compiler change.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.