3 个版本 (重大更改)
0.3.0 | 2021 年 11 月 3 日 |
---|---|
0.2.0 | 2021 年 11 月 3 日 |
0.1.0 | 2021 年 11 月 2 日 |
#2079 在 Rust 模式
8KB
Clonesure
一个辅助宏,用于创建将克隆其环境的闭包。
安装
将以下行添加到您的 Cargo.toml 文件中
clonesure = "0.3.0"
入门
在定义闭包的参数时,使用 @var
来克隆变量,使用 @mut var
来克隆可变变量。
克隆的变量必须放在闭包参数之前。
例如。
cc!(|@a, @mut b, c| a + b + c)
将翻译为
{
let a = a.clone();
let mut b = b.clone();
move |c| a + b + c
}
示例
use clonesure::cc;
fn main() {
// `cc` will implicitly move its environment
let s1 = String::from("111");
let s2 = String::from("222");
assert_eq!(
// implicitly move s1 into the closure
// brackets of the closure's body are optional
cc!(|| s1)(),
"111"
);
assert_eq!(
// explicitly move s2 into the closure
cc!(move || s2)(),
"222"
);
// clone one var
let s1 = String::from("111");
assert_eq!(
// clone s1 into the closure
cc!(|@s1| s1)(),
"111"
);
assert_eq!(
s1, // the original s1 is still alive
"111",
);
// clone many vars
let s1 = String::from("111");
let s2 = String::from("222");
assert_eq!(cc!(|@s1, @s2| s1 + &s2)(), "111222");
// clone var mut
let s1 = String::from("111");
let s2 = String::from("222");
assert_eq!(
cc!(|@mut s1, @s2| {
s1 = s1 + &s2;
s1
})(),
"111222"
);
// with closure params
// cloned vars must be in front of closure params
let s1 = String::from("111");
let s2 = String::from("222");
let s3 = String::from("333");
assert_eq!(
cc!(|@mut s1, @s2, s3| {
s1 = s1 + &s2 + s3;
s1
})(&s3),
"111222333"
);
// param type, param pattern, return type
let s1 = String::from("111");
let s2 = String::from("222");
let s3 = String::from("333");
let s4 = 444;
assert_eq!(
cc!(|@mut s1, @s2, s3: String, &s4| -> String {
s1 = s1 + &s2 + &s3;
format!("{}{}", s1, s4)
})(s3, &s4),
"111222333444"
);
}