Skip to content

Commit f19e751

Browse files
diannetraviscross
authored andcommitted
Specify relative drop order of pattern bindings
Edited-by: TC
1 parent 5b3ca00 commit f19e751

File tree

1 file changed

+43
-3
lines changed

1 file changed

+43
-3
lines changed

src/destructors.md

Lines changed: 43 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -185,9 +185,48 @@ let declared_first = PrintOnDrop("Dropped last in outer scope");
185185
let declared_last = PrintOnDrop("Dropped first in outer scope");
186186
```
187187

188-
r[destructors.scope.bindings.match-pattern-order]
189-
If multiple patterns are used in the same arm for a `match` expression, then an
190-
unspecified pattern will be used to determine the drop order.
188+
r[destructors.scope.bindings.pattern-drop-order]
189+
If a pattern binds multiple variables, they are dropped in reverse order of declaration.
190+
191+
```rust
192+
# struct PrintOnDrop(&'static str);
193+
# impl Drop for PrintOnDrop {
194+
# fn drop(&mut self) {
195+
# println!("drop({})", self.0);
196+
# }
197+
# }
198+
let (declared_first, declared_last) = (
199+
PrintOnDrop("Dropped last"),
200+
PrintOnDrop("Dropped first"),
201+
);
202+
```
203+
204+
r[destructors.scope.bindings.or-pattern-declaration-order]
205+
For the purpose of drop order, [or-patterns] declare their bindings in the order given by their first sub-pattern.
206+
207+
```rust
208+
# struct PrintOnDrop(&'static str);
209+
# impl Drop for PrintOnDrop {
210+
# fn drop(&mut self) {
211+
# println!("drop({})", self.0);
212+
# }
213+
# }
214+
// Drops `declared_last`, then `declared_first`.
215+
fn fixed_variable_drop_order<T>(
216+
(Ok([declared_first, declared_last])
217+
| Err([declared_last, declared_first])): Result<[T; 2], [T; 2]>
218+
) {}
219+
220+
fixed_variable_drop_order(Ok([
221+
PrintOnDrop("Dropped last"),
222+
PrintOnDrop("Dropped first"),
223+
]));
224+
225+
fixed_variable_drop_order(Err([
226+
PrintOnDrop("Dropped first"),
227+
PrintOnDrop("Dropped last"),
228+
]));
229+
```
191230

192231
r[destructors.scope.temporary]
193232
### Temporary scopes
@@ -473,6 +512,7 @@ There is one additional case to be aware of: when a panic reaches a [non-unwindi
473512
[Trait objects]: types/trait-object.md
474513
[tuple]: types/tuple.md
475514

515+
[or-patterns]: patterns.md#or-patterns
476516
[slice pattern]: patterns.md#slice-patterns
477517
[struct pattern]: patterns.md#struct-patterns
478518
[tuple pattern]: patterns.md#tuple-patterns

0 commit comments

Comments
 (0)