如何编写可以组成`FnMut`闭包的函数?

时间:2016-03-29 12:43:24

标签: closures rust

这是一个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))
}

如何使这个撰写函数可以关闭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闭包?

1 个答案:

答案 0 :(得分:2)

局部变量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)))
}