Skip to main content

clone_block/
lib.rs

1/**************************************************************************************************
2 *                                                                                                *
3 * This Source Code Form is subject to the terms of the Mozilla Public                            *
4 * License, v. 2.0. If a copy of the MPL was not distributed with this                            *
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/.                                       *
6 *                                                                                                *
7 **************************************************************************************************/
8
9// ======================================== Documentation ======================================= \\
10
11//! A very simple macro that clones a list of variables before calling an expression.
12//!
13//! Based on this tweet: <https://twitter.com/untitaker/status/1299812136202493953>
14//!
15//! ## Example
16//!
17//! ```rust
18//! use clone_block::clone;
19//! use std::thread;
20//!
21//! let foo = "foo".to_string();
22//!
23//! let thread = thread::spawn(
24//!     clone!(foo; move || {
25//!         let foobar = format!("{}bar", foo);
26//!         foobar
27//!     })
28//! );
29//!
30//! let foobar = thread.join();
31//! let foobaz = format!("{}baz", foo);
32//! ```
33
34// ======================================== macro_rules! ======================================== \\
35
36#[macro_export]
37/// ## Example
38///
39/// ```rust
40/// use clone_block::clone;
41/// use std::thread;
42///
43/// let foo = "foo".to_string();
44///
45/// let thread = thread::spawn(
46///     clone!(foo; move || {
47///         let foobar = format!("{}bar", foo);
48///         foobar
49///     })
50/// );
51///
52/// let foobar = thread.join();
53/// let foobaz = format!("{}baz", foo);
54/// ```
55macro_rules! clone {
56    ($($var:ident),+ ; $expr:expr) => {{
57        $(let $var = $var.clone();)+
58
59        $expr
60    }};
61}