我想寫一個組成兩個函數的函數,最初的設計很簡單,一個函數接受兩個函數並返回一個組合函數,然後我可以用其他函數編寫,(因爲鐵鏽沒有剩餘參數)。但是我遇到了一個漫長而艱難的環境,用令人沮喪的無用編譯器錯誤構建。如何編寫防鏽功能?
我的構建功能:
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 –
並不適用於我的情況。 –