Skip to content

Commit

Permalink
Lifetime and scope clarification in Closure types reference.
Browse files Browse the repository at this point in the history
As I understood so far, lifetime is affecting the borrowing rules enforcement, scope on the other hand, has to do with memory deallocation.
Most of the time, these two concepts are not overlapped.
The only case I'm aware they do, is that of the temporary variables in `let` statements.
  • Loading branch information
stegrams authored Dec 6, 2023
1 parent 692d216 commit edc92b1
Showing 1 changed file with 9 additions and 8 deletions.
17 changes: 9 additions & 8 deletions src/types/closure.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,12 +95,12 @@ reference, as in the following example:
```rust
let mut b = false;
let x = &mut b;
{
let mut c = || { *x = true; };
// The following line is an error:
// let y = &x;
c();
}

let mut c = || { *x = true; };
// The following line is an error:
// let y = &x;
c();

let z = &x;
```

Expand All @@ -110,8 +110,9 @@ because a `& &mut` reference might not be unique, so it cannot safely be used to
modify a value. So a unique immutable borrow is used: it borrows `x` immutably,
but like a mutable borrow, it must be unique. In the above example, uncommenting
the declaration of `y` will produce an error because it would violate the
uniqueness of the closure's borrow of `x`; the declaration of z is valid because
the closure's lifetime has expired at the end of the block, releasing the borrow.
uniqueness of the closure's borrow of `x`; the declaration of `z` is valid because
the closure's lifetime has expired, i.e. there are no `c` calls after `z`,
releasing the borrow.

## Call traits and coercions

Expand Down

0 comments on commit edc92b1

Please sign in to comment.