#4.6. Capture semantics
On this page
- 4.6.1. Default: value copy
- 4.6.2. Reference capture: the [ref x] capture list
- Multiple and mixed captures
- 4.6.3. Tokenization of capture lists
- 4.6.4. Reassigning an outer variable in the body → ref required
- 4.6.5. ref shorthand (none)
- 4.6.6. Automatic handling of loop variables
- 4.6.7. Capturing structs and reference handles
- 4.6.8. ref capture vs object mutation
- 4.6.9. Additional constraints in parallel and concurrent contexts
- 4.6.10. Lifetime of captured variables
- 4.6.11. Move capture: the [move x] capture list
A closure can capture variables from the outer environment. This chapter defines the rules that determine whether a capture copies a value or holds a reference.
#4.6.1. Default: value copy
Important
The default meaning of a capture is value copy. When the closure is created, a snapshot of the outer variable's value is taken.
let count = 0;
let f = || { count + 1 }; // the value 0 of count is copied
count = 10;
f(); // 1 (f holds 0)
This decision has three motivations. First, explicitness: the capture mode is clearly visible in the code. Second, blocking side effects: it prevents the pitfall of a closure silently modifying an outer variable. Third, friendliness to scientific and numeric code: it avoids Julia's 100x boxing pitfall, where reference captures are boxed into dynamic slots and degrade performance.
capture_list ::= "[" capture_item ("," capture_item)* ","? "]"
capture_item ::= "ref" capture_name | "move" capture_name | capture_name
capture_name ::= identifier | "self"
self names a method's receiver. [ref self] is allowed only in a ref self method, where it shares the receiver (4.7.4); a by-value self is captured by value.
#4.6.2. Reference capture: the [ref x] capture list
To capture a reference to an outer variable's binding, use an explicit capture list.
let count = 0;
let inc = [ref count] || { count = count + 1 };
let dec = [ref count] || { count = count - 1 };
inc(); inc(); dec();
// count = 1
The list is written before the closure definition, as [ref var, ref var, ...]. Variables in the list are held in a shared cell (boxing); the outer scope and the closure use the same cell, so reassigning inside the closure is reflected in the outer variable. The cell is a GC object, so the closure may outlive the variable's scope. Variables not in the list are captured by value as usual.
#Multiple and mixed captures
let counter = 0;
let config = load_config();
let handler = [ref counter] || {
counter = counter + 1; // ref: reflected in the outer variable
print(config.version); // value: snapshot of config at capture time
};
Only the variables named in the capture list are ref captures; the rest are automatically captured by value.
#4.6.3. Tokenization of capture lists
[ref x] || body is tokenized as follows: [, ref, x, ] form the bracketed capture list, and || or |x| marks the start of the closure.
Ambiguity is resolved by the longest-match rule of punctuation and operator tokens and by context. If [...] is immediately followed by || or |x|, it is a capture list; otherwise it is ordinary indexing or an array literal.
let xs = [1, 2, 3]; // List literal
let f = [ref count] || { ... }; // capture list + closure
arr[ref count] // ERROR (E0010): ref cannot be used in indexing
#4.6.4. Reassigning an outer variable in the body → ref required
Attempting to reassign a value-captured outer variable in the closure body is a compile error (E0057).
let count = 0;
let f = || { count = count + 1 };
// ERROR (E0057): `count` is value-captured; to mutate the outer variable,
// add `[ref count]` to the closure's capture list
This rule guides the user to state a ref capture deliberately.
#4.6.5. ref shorthand (none)
ref || { ... } // not adopted
There is no shorthand that ref-captures everything. A capture can become ref only through an explicit list, so that the code clearly shows which variables are held by reference.
#4.6.6. Automatic handling of loop variables
Because value capture is the default, each iteration's loop variable keeps its own value.
let fns: List<fn() -> i32> = [];
for i in 0i32..5i32 {
fns.push(|| i); // copies the value of i in each iteration
}
fns[0](); // 0
fns[4](); // 4
No separate rule like Go 1.22's per-iteration scope is needed; value capture produces the intended meaning automatically.
#4.6.7. Capturing structs and reference handles
Value capture copies the value into the closure. A struct is a value type, so the closure holds its own copy; a field write inside the closure does not reach the outer variable. Use [ref p] for that. A field write on a value capture is a compile error (E0057), as rebinding the capture is, with the help add `[ref p]` to the closure's capture list. So is a call of a ref self method on a value capture of plain data (numbers, bool, str, and structs, tuples, arrays and enums of them without a Drop), or on a field of one: each call of the closure starts from its own copy, so the change would be lost (List::from_fn(4, |_| g.uniform(0.0, 1.0)) with a seeded generator g gives one value four times). Handles and resources that share their state (Cell, File, a socket) are not affected. Write [ref g] |_| g.uniform(0.0, 1.0); to change a copy inside the closure only, copy it into a local variable first.
Collections (List, Dict, Set, StrBuf, ...) are reference handles (stdlib 2.9). Value capture copies the handle, so the object is shared.
let xs = [1, 2, 3];
let f = || { xs.push(4) }; // copies the handle (same List)
f();
// xs == [1, 2, 3, 4]
let p = Point { x: 0.0, y: 0.0 };
let g = [ref p] || { p.x = 1.0 }; // ref capture: writes the outer p
g();
// p.x == 1.0
For an independent copy of a collection, call .clone().
#4.6.8. ref capture vs object mutation
let xs = [1, 2, 3];
// value capture: mutating the object is OK, reassigning the binding is not
let f = || {
xs.push(4); // OK: object mutation
// xs = []; // ERROR: binding reassignment
};
// ref capture: reassigning the binding is also allowed
let g = [ref xs] || {
xs = []; // OK: the outer xs becomes []
};
For a reference handle, value capture and object mutation go together, since the object is shared. ref capture is used when the binding itself must be reassigned.
This distinction is the same as the self and ref self model of impl.
#4.6.9. Additional constraints in parallel and concurrent contexts
Every plain capture of a fn() + Send closure (one passed to task::spawn_blocking, par::for_each, thread::spawn, etc.) must be Send + Sync (4.4): the closure shares it with the code that made it. A [move x] capture is the closure's alone and needs only Send (4.6.11); a + Sync closure (par::for_each, which every worker calls) needs every capture Sync. A [ref x] cell is written by both the closure and the code that created it, so it is never Send or Sync, whatever the type of x: a closure with a [ref] capture (or one that captures such a closure, or a future made by an async [ref x] || closure) fits no + Send / + Sync slot. Same-thread uses (spawn_local, ordinary calls) are unaffected. Collections are !Sync (stdlib 2.13.9) and cannot be value-captured this way either.
let buf: List<i32> = [];
par::for_each(xs, [ref buf] |x| { buf.push(x) });
// ERROR (E0085): a [ref buf] cell cannot cross threads
Instead, use a fold (par::fold(xs, 0, |a, b| a + b)), share through Mutex / RwLock / Atomic / channels, or return the value from the thread (join()). A value only the spawned code needs is moved in: thread::spawn([move buf] || buf.len()).
A value shared this way belongs to its new owner: after Mutex::new(buf) or tx.send(buf), using buf is a compile error (E0105, stdlib 2.13.9). Use it through the lock, or hand over buf.clone().
let m = Mutex::new(buf);
buf.push(1);
// ERROR (E0105): `buf` was moved into the `Mutex` at line 1
// help: use it through the lock: using g = m.lock() { g.get().push(1) }
The detailed parallelism and concurrency rules are defined by the standard library specification; this chapter covers only the language-level capture mechanism.
A captured Drop resource (a File, a socket, a channel Sender) is not copied: the capture moves it into the closure or async block, and using it outside afterwards is an error (stdlib 2.13.4). An async block's task releases what it captured when it ends, for a value whose release cannot fail (a Sender); a captured value whose close can fail (a File) must be closed inside the block (try f.close() or using), or the block is an error (E0134). To keep a value outside too, capture a copy: x.clone(), or try x.try_clone() for a File.
#4.6.10. Lifetime of captured variables
Captured variables live as long as the closure value. Even after the closure leaves the outer scope, the captured values are kept inside the closure object.
fn make_counter() -> fn() -> i32 {
let count = 0;
[ref count] || { count = count + 1; count }
// count is captured by ref; kept until the closure goes away
}
let c = make_counter();
c(); // 1
c(); // 2
c(); // 3
In this example, count stays alive, attached to the closure object, after the outer function returns. The GC manages this lifetime (7. Runtime Model).
#4.6.11. Move capture: the [move x] capture list
[move x] gives x to the closure when the closure is made. It is the counterpart of [ref x]: a ref capture shares the binding with the code that made the closure, a move capture leaves that code without it.
let rows: List<str> = load();
let t = thread::spawn([move rows] || rows.len());
rows.push("x");
// ERROR (E0105): `rows` was moved into a closure at line 2
// help: the closure owns it now; use it inside the closure, ...
- Making the closure hands
xover as a channel send does (stdlib 2.13.9): the closure gets a copy of every collectionxreaches, and usingx(or another handle to what it holds) afterwards is a compile error (E0105). ASyncvalue (a number, astr, an array of them) is exempt: the closure's copy andxare equal and may both be used. - A moved capture needs only
Sendfor the closure to cross threads: no other code reaches it. So a collection, aCommandor aChildmay go tothread::spawn,task::spawn_blockingorpar::Scope::spawn. Plain captures keep theSend + Syncrule of 4.6.9, and a+ Syncslot (par::for_each, which every worker calls) needs every captureSync. - A closure that owns a moved capture that is not
Syncis handed over once. Passing it to a parameter typedfn(..) + SendwithoutSynchands it over, whatever the function: such a parameter is one the callee may run on another thread (thread::spawn,thread::Builder::spawn,task::spawn_blocking,task::spawn_blocking_with_arg'sf,par::join,par::Scope::spawn,par::TryScope::spawn, and any function of the program's own with such a parameter). Using it again afterwards, however it travels (a variable, a struct or tuple field, a list element, a parameter, anif/matcharm, the result of a function that returns its argument), is a compile error (E0133); so is passing it twice to one call (par::join(f, f)). Afn(..) + Sendvalue whose type does not saySyncmay own such a capture, so it is handed over once too;+ Send + Syncvalues and closures whose captures are allSend + Synccan be passed again. Calling a closure does not hand it over: it may be called any number of times. To run the same work twice on other threads, make two closures, each moving in its own.clone(). - Calling an
async [move ..]closure does not hand it over either, but the future the call makes runs on what the closure moved in: the closure and each of its futures are one owner. Its futures may be awaited here one after another (await f(); await f();); handing the closure or one of its futures over (totask::spawn, into another closure's[move f]) takes the others along, and using them afterwards is a compile error (E0105/E0133).
let xs: List<i32> = [];
let f = async [move xs] || { xs.push(1); xs.len() };
let a = await f(); // OK: runs here
let t = task::spawn(f()); // the task owns f's moved values now
let b = await f();
// ERROR (E0133): a future of `f` was spawned as a task at line 4, and every future
// of an `async [move ..]` closure shares what it moved in
- A must-close value (a
File, a socket) moves into the closure as a plain capture already does (4.6.9); the closure closes it. moveandrefmix in one list ([move xs, ref n]); one name may not be both. A name in the list that the body does not use is not captured.
let xs: List<i32> = [1, 2];
let n = 0;
let f = [move xs, ref n] || { n += 1; xs.push(n) }; // OK, on this thread
let g = [ref n, move n] || n; // ERROR (E0058): both ref and move
The same value can be passed as an argument instead: task::spawn_blocking_with_arg(xs, |xs| xs.len()) (stdlib 2.18.1).
Found a mistake? Edit this page on GitHub. Last updated