1 #### Note: this error code is no longer emitted by the compiler.
3 This error occurs when an attempt is made to mutate or mutably reference data
4 that a closure has captured immutably.
6 Erroneous code example:
9 // Accepts a function or a closure that captures its environment immutably.
10 // Closures passed to foo will not be able to mutate their closed-over state.
11 fn foo<F: Fn()>(f: F) { }
13 // Attempts to mutate closed-over data. Error message reads:
14 // `cannot assign to data in a captured outer variable...`
20 // Attempts to take a mutable reference to closed-over data. Error message
21 // reads: `cannot borrow data mutably in a captured outer variable...`
24 foo(|| { let y = &mut x; });
28 The problem here is that foo is defined as accepting a parameter of type `Fn`.
29 Closures passed into foo will thus be inferred to be of type `Fn`, meaning that
30 they capture their context immutably.
32 If the definition of `foo` is under your control, the simplest solution is to
33 capture the data mutably. This can be done by defining `foo` to take FnMut
37 fn foo<F: FnMut()>(f: F) { }
40 Alternatively, we can consider using the `Cell` and `RefCell` types to achieve
41 interior mutability through a shared reference. Our example's `mutable`
42 function could be redefined as below:
47 fn foo<F: Fn()>(f: F) { }
50 let x = Cell::new(0u32);
55 You can read more about cell types in the API documentation:
57 https://doc.rust-lang.org/std/cell/