Skip to content

Commit bf143cf

Browse files
committed
Revise examples for main discriminant reads rule
The example here showed what isn't captured, but it didn't demonstrate what is captured. Let's show both. We'll specifically use a non-`Copy` type for this because [Rust PR #138961] affects the behavior in the non-`Copy` case. [Rust PR #138961]: rust-lang/rust#138961
1 parent 15302fa commit bf143cf

File tree

1 file changed

+26
-12
lines changed

1 file changed

+26
-12
lines changed

src/types/closure.md

Lines changed: 26 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -294,19 +294,33 @@ If pattern matching reads a discriminant, the place containing that discriminant
294294
r[type.closure.capture.precision.discriminants.multiple-variant]
295295
Matching against a variant of an enum that has more than one variant reads the discriminant, capturing the place by `ImmBorrow`.
296296

297-
```rust
298-
enum Example {
299-
A(i32),
300-
B(i32),
301-
}
302-
303-
let mut x = (Example::A(21), 37);
297+
```rust,compile_fail,E0502
298+
struct S; // A non-`Copy` type.
299+
let mut x = (Some(S), S);
300+
let c = || match x {
301+
(None, _) => (),
302+
// ^^^^
303+
// This pattern requires reading the discriminant, which
304+
// causes `x.0` to be captured by `ImmBorrow`.
305+
_ => (),
306+
};
307+
let _ = &mut x.0; // ERROR: Cannot borrow `x.0` as mutable.
308+
// ^^^
309+
// The closure is still live, so `x.0` is still immutably
310+
// borrowed here.
311+
c();
312+
```
304313

305-
let c = || match x { // captures `x.0` by ImmBorrow
306-
(Example::A(_), _) => println!("variant A"),
307-
(Example::B(_), _) => println!("variant B"),
308-
};
309-
x.1 += 1; // x.1 can still be modified
314+
```rust,no_run
315+
# struct S; // A non-`Copy` type.
316+
# let x = (Some(S), S);
317+
let c = || match x { // Captures `x.0` by `ImmBorrow`.
318+
(None, _) => (),
319+
_ => (),
320+
};
321+
// Though `x.0` is captured due to the discriminant read,
322+
// `x.1` is not captured.
323+
x.1; // OK: `x.1` can be moved here.
310324
c();
311325
```
312326

0 commit comments

Comments
 (0)