|
|
@ -3,24 +3,42 @@
|
|
|
|
## Description
|
|
|
|
## Description
|
|
|
|
|
|
|
|
|
|
|
|
By default, closures capture their environment by borrowing. Or you can use `move`-closure
|
|
|
|
By default, closures capture their environment by borrowing. Or you can use `move`-closure
|
|
|
|
to move environment. However, often you want to give copy of some data to closure.
|
|
|
|
to move environment. However, often you want to give copy of some data to closure, pass it
|
|
|
|
|
|
|
|
by reference, or perform some other transformation.
|
|
|
|
|
|
|
|
|
|
|
|
Use variable rebinding in separate scope for that.
|
|
|
|
Use variable rebinding in separate scope for that.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
## Example
|
|
|
|
## Example
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Use
|
|
|
|
|
|
|
|
|
|
|
|
```rust
|
|
|
|
```rust
|
|
|
|
let mut num = Rc::new(5);
|
|
|
|
let num1 = Rc::new(1);
|
|
|
|
|
|
|
|
let num2 = Rc::new(2);
|
|
|
|
|
|
|
|
let num3 = Rc::new(3);
|
|
|
|
let closure = {
|
|
|
|
let closure = {
|
|
|
|
let num = num.clone();
|
|
|
|
// `num1` is moved
|
|
|
|
move || {
|
|
|
|
let num2 = num2.clone(); // `num2` is cloned
|
|
|
|
*num + 10
|
|
|
|
let num3 = num3.as_ref(); // `num3` is borrowed
|
|
|
|
}
|
|
|
|
move || {
|
|
|
|
|
|
|
|
*num1 + *num2 + *num3;
|
|
|
|
|
|
|
|
}
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
// Instead of
|
|
|
|
instead of
|
|
|
|
let num_copy = num.clone();
|
|
|
|
|
|
|
|
let closure = move || { *num_copy + 10 };
|
|
|
|
```rust
|
|
|
|
|
|
|
|
let num1 = Rc::new(1);
|
|
|
|
|
|
|
|
let num2 = Rc::new(2);
|
|
|
|
|
|
|
|
let num3 = Rc::new(3);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
let num2_cloned = num2.clone();
|
|
|
|
|
|
|
|
let num3_borrowed = num3.as_ref();
|
|
|
|
|
|
|
|
let closure = move || {
|
|
|
|
|
|
|
|
*num1 + *num2_cloned + *num3_borrowed;
|
|
|
|
|
|
|
|
};
|
|
|
|
```
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@ -31,3 +49,8 @@ and they will be dropped immediately even if they are not consumed by closure.
|
|
|
|
|
|
|
|
|
|
|
|
Closure uses same variable names as surrounding code whether data are copied or moved.
|
|
|
|
Closure uses same variable names as surrounding code whether data are copied or moved.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
## Disadvantages
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Additional indentation of closure body.
|
|
|
|
|
|
|
|
|
|
|
|