如何编写一个可以构成FnMut闭包的函数? [英] How do I write a function that can compose `FnMut` closures?

查看:45
本文介绍了如何编写一个可以构成FnMut闭包的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Here's a compose function that can compose Fn closures:

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 闭包?我试过了:

How do I make it so that this compose function can take FnMut closures? I tried:

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 闭包一起使用?

Extending this, can it be made to work with FnOnce closures?

推荐答案

局部变量 f g 必须是可变的:

Local variables f and g must be mutable:

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)))
}

这篇关于如何编写一个可以构成FnMut闭包的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆