From 72606ccfcbf3879a22f084c9abdf369cf6a57fbd Mon Sep 17 00:00:00 2001 From: Mikhail Trishchenkov Date: Fri, 23 Sep 2016 22:45:14 +0700 Subject: [PATCH] Clone to closure idiom --- README.md | 1 + idioms/clone-to-closure.md | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 idioms/clone-to-closure.md diff --git a/README.md b/README.md index d486f6b..e7f9964 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ language. * TODO interior mutability - UnsafeCell, Cell, RefCell * TODO treating Option like a list * TODO `Default` trait +* [Pass clone to closure](idioms/clone-to-closure.md) ### Design patterns diff --git a/idioms/clone-to-closure.md b/idioms/clone-to-closure.md new file mode 100644 index 0000000..30266fa --- /dev/null +++ b/idioms/clone-to-closure.md @@ -0,0 +1,33 @@ +# Pass clone to closure + +## 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. +Use variable rebinding in separate scope for that. + + +## Example + +```rust +let mut num = Rc::new(5); +let closure = { + let num = num.clone(); + move || { + *num + 10 + } +}; + +// Instead of +let num_copy = num.clone(); +let closure = move || { *num_copy + 10 }; +``` + + +## Advantages + +Copied data are grouped together with closure definition, so their purpose is more clear +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. +