我想写一个组成两个函数的函数,最初的设计很简单,一个函数接受两个函数并返回一个组合函数,然后我可以用其他函数编写,(因为铁锈没有剩余参数)。但是我遇到了一个漫长而艰难的环境,用令人沮丧的无用编译器错误构建。如何编写防锈功能?
我的构建功能:
fn compose<'a, A, B, C, G, F>(f: F, g: G) -> Box<Fn(A) -> C + 'a>
where F: 'a + Fn(A) -> B + Sized, G: 'a + Fn(B) -> C + Sized
{
Box::new(move |x| g(f(x)))
}
我想怎样使用它:
fn main() {
let addAndMultiply = compose(|x| x * 2, |x| x + 2);
let divideAndSubtract = compose(|x| x/2, |x| x - 2);
let finally = compose(*addAndMultiply, *divideAndSubtract);
println!("Result is {}", finally(10));
}
rustc不喜欢,不管我怎么努力,特质界永远不会满足。错误是:
➜ cargo run
Compiling flowtree v0.1.0 (file:///home/seunlanlege/Projects/flowtree)
error[E0277]: the trait bound `std::ops::Fn(_) -> _: std::marker::Sized` is not satisfied
--> src/main.rs:11:19
|
11 | let finally = compose(*addAndMultiply, *divideAndSubtract);
| ^^^^^^^ the trait `std::marker::Sized` is not implemented for `std::ops::Fn(_) -> _`
|
= note: `std::ops::Fn(_) -> _` does not have a constant size known at compile-time
= note: required by `compose`
error[E0277]: the trait bound `std::ops::Fn(_) -> _: std::marker::Sized` is not satisfied
--> src/main.rs:11:19
|
11 | let finally = compose(*addAndMultiply, *divideAndSubtract);
| ^^^^^^^ the trait `std::marker::Sized` is not implemented for `std::ops::Fn(_) -> _`
|
= note: `std::ops::Fn(_) -> _` does not have a constant size known at compile-time
= note: required by `compose`
error: aborting due to 2 previous errors
error: Could not compile `flowtree`.
To learn more, run the command again with --verbose.
作为主要目标,你可能会寻找这样的:https://stackoverflow.com/q/36284637/1233251 –
并不适用于我的情况。 –