Skip to content

Commit d83a0fd

Browse files
committed
add diagnostics for E0387
1 parent 920cf4b commit d83a0fd

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed

src/librustc_borrowck/diagnostics.rs

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,42 @@ fn main(){
9595
x = 5;
9696
}
9797
```
98+
"##,
99+
100+
E0387: r##"
101+
This error occurs when an attempt is made to mutate or mutably reference data
102+
that a closure has captured immutably. Examples of this error are shown below:
103+
104+
```
105+
// Accepts a function or a closure that captures its environment immutably.
106+
// Closures passed to foo will not be able to mutate their closed-over state.
107+
fn foo<F: Fn()>(f: F) { }
108+
109+
// Attempts to mutate closed-over data. Error message reads:
110+
// `cannot assign to data in a captured outer variable...`
111+
fn mutable() {
112+
let mut x = 0u32;
113+
foo(|| x = 2);
114+
}
115+
116+
// Attempts to take a mutable reference to closed-over data. Error message
117+
// reads: `cannot borrow data mutably in a captured outer variable...`
118+
fn mut_addr() {
119+
let mut x = 0u32;
120+
foo(|| { let y = &mut x; });
121+
}
122+
```
123+
124+
The problem here is that foo is defined as accepting a parameter of type `Fn`.
125+
Closures passed into foo will thus be inferred to be of type `Fn`, meaning that
126+
they capture their context immutably.
127+
128+
The solution is to capture the data mutably. This can be done by defining `foo`
129+
to take FnMut rather than Fn:
130+
131+
```
132+
fn foo<F: FnMut()>(f: F) { }
133+
```
98134
"##
99135

100136
}
@@ -104,7 +140,6 @@ register_diagnostics! {
104140
E0383, // partial reinitialization of uninitialized structure
105141
E0385, // {} in an aliasable location
106142
E0386, // {} in an immutable container
107-
E0387, // {} in a captured outer variable in an `Fn` closure
108143
E0388, // {} in a static location
109144
E0389 // {} in a `&` reference
110145
}

0 commit comments

Comments
 (0)