let add = |x, y| x + y; let result = do1(add, 5); println!("result(1) => {}", result(1)); } 输出 result(1) => 6
下面我们考虑一下是否可以做一个通用的
1 2 3 4 5
fn do2<F, X, Y, Z>(f: F, x: X) -> impl Fn(Y) -> Z where F: Fn(X, Y) -> Z{ move |y| f(x, y) }
报错如下
1 2 3 4 5 6 7 8 9 10 11 12
error[E0507]: cannot move out of `x`, a captured variable in an `Fn` closure --> src/main.rs:12:16 | 9 | fn do2<F, X, Y, Z>(f: F, x: X) -> impl Fn(Y) -> Z | - captured outer variable ... 12 | move |y| f(x, y) | -----------^---- | | | | | move occurs because `x` has type `X`, which does not implement the `Copy` trait | captured by this `Fn` closure
下面我们修改代码
1 2 3 4 5 6 7 8 9 10 11 12 13
fn do2<F, X, Y, Z>(f: F, x: X) -> impl Fn(Y) -> Z where F: Fn(X, Y) -> Z, X: Copy{ move |y| f(x, y) } fn main(){ let add = |x, y| x + y; let result = do2(add, 5); println!("result(2) => {}", result(2)); } 输出 result(2) => 7