diff --git a/idioms/clone-to-closure.md b/idioms/clone-to-closure.md index 30266fa..1f0f9e9 100644 --- a/idioms/clone-to-closure.md +++ b/idioms/clone-to-closure.md @@ -3,24 +3,42 @@ ## Description 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. ## Example +Use + ```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 num = num.clone(); - move || { - *num + 10 - } + // `num1` is moved + let num2 = num2.clone(); // `num2` is cloned + let num3 = num3.as_ref(); // `num3` is borrowed + move || { + *num1 + *num2 + *num3; + } }; +``` -// Instead of -let num_copy = num.clone(); -let closure = move || { *num_copy + 10 }; +instead of + +```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. + +## Disadvantages + +Additional indentation of closure body. +