Skip to content

No spelling mutates an outer Copy binding from a closure (§12.4 captures Copy by copy; a write to the copy is now rejected) #1586

Closed

Description

@ehartford

From the #1486 decision (stack #1585). §12.4: "For Copy values, default capture copies the value." — so run_unit(() => n += 1) writes the closure's copy and the outer n stays unchanged; that is the specified behavior. Because the language has no spelling to mutate an outer Copy binding from a closure, a write to the copy is almost always a mistake, and #1584's stack makes it a compile error:

error: assignment to `n` writes the closure's copy of a `Copy` capture; the outer `n` is unchanged (§12.4). Declare `n` inside the closure, or keep the value in a non-Copy cell (a one-element Vec) and mutate that

The gap for a ruling: a counter, an accumulator or a flag updated from a closure (items |> for_each(x => total += x), spawn's worker bumping a var done) has no direct spelling. Non-Copy captures are by place, so the workaround is a non-Copy cell (Vec[i32] with one element, a struct with a mut fn), which is ceremony for the most common closure side effect. Candidates: a ref capture spelling ((ref total) => total += x), an inferred by-place mode when the body assigns (Rust's unique-borrow capture — but §12.4's Copy rule then has an exception), or a Cell[T] in the stdlib. move || is not this: it copies too.

Rejected in the stack: = and compound assignment to a Copy capture in a non-move, non-scoped-spawn closure (fixtures under test/compile_errors/err_closure_copy_capture_assign*). move closures may still assign their own copy (test/mut_move_closure.w case 1).

Activity

  1. ehartford commented on Sep 23, 2026

    @ehartford
    ContributorAuthor

    Ruled (Eric, 2026-09-23; spec §12.4 / D62, #1593): captures are by place regardless of Copy, always — not only when the body writes. count += 1 inside a non-move closure mutates the outer count; the snapshot is move ||. The "assignment to a Copy capture" diagnostic from #1486 is retired before reaching main; stack #1585 is being reworked to the ruling.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions