这是一个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
闭包?
答案 0 :(得分:2)
局部变量f
和g
必须是可变的:
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)))
}