这是一个可以构成compose闭包的Fn函数:

fn compose<'a, T1, T2, T3, F1, F2>(f: F1, g: F2) -> Box<Fn(T1) -> T3 + 'a>
    where F1: Fn(T1) -> T2 + 'a,
          F2: Fn(T2) -> T3 + 'a
{
    box move |x| g(f(x))
}

我如何做到这一点,以便此compose函数可以采用FnMut闭包?我试过了:
fn compose<'a, T1, T2, T3, F1, F2>(f: F1, g: F2) -> Box<FnMut(T1) -> T3 + 'a>
    where F1: FnMut(T1) -> T2 + 'a,
          F2: FnMut(T2) -> T3 + 'a
{
    box move |x| g(f(x))
}

但它提示:
error: cannot borrow captured outer variable in an `FnMut` closure as mutable
         box move |x| g(f(x))
                      ^
error: cannot borrow captured outer variable in an `FnMut` closure as mutable
         box move |x| g(f(x))
                        ^

扩展这一点,是否可以使其与FnOnce闭包一起使用?

最佳答案

局部变量fg必须是可变的:

fn compose<'a, T1, T2, T3, F1, F2>(mut f: F1, mut g: F2) -> Box<FnMut(T1) -> T3 + 'a>
    where F1: FnMut(T1) -> T2 + 'a,
          F2: FnMut(T2) -> T3 + 'a
{
    Box::new(move |x| g(f(x)))
}

关于closures - 如何编写可以构成 `FnMut`闭包的函数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36284637/

10-15 03:19