1个不稳定版本
0.1.0 | 2021年11月21日 |
---|
#1707 in Rust模式
用于decurse
7KB
102 行
PFn
为具有≤ 12个参数的函数/闭包在稳定版Rust上提供fn_trait
的call
、call_mut
和call_once
。
示例
基本用法
let closure = |x: i32, y: i32, z: String| {
println!("{}", z);
x + y
};
// Once the `fn_trait` feature has stabilized, you would do this.
let result = closure.call((5, 42, "Hello World"));
// For now, use PFn.
let result = closure.pfn_call((5, 42, "Hello World"));
泛化不同参数数量的函数
// Here, Func can be a function or closure that takes any number of arguments (actually 1 - 12 arguments).
struct Runnable<Args, Func: PFnOnce<Args>> {
func: Func,
args: Args
}
impl<Args, Func: PFnOnce<Args>> Runnable<Args, Func> {
fn run(self) -> Func::PFnOutput {
(self.func).pfn_call_once(self.args)
}
}
let runnable = Runnable {
func: |mut x: String| {
x.push_str("!!!");
x
},
args: ("hello world".into(),)
};
assert_eq!(runnable.run(), "hello world!!!");