I read this already, but it did not help me since it was talking about specific function.
Is it possible to make a recursive closure in Rust?
What I want to do is this: pass the function and how many time will I repeat the function call, and get the function as return, so func_n(2, f)(x)
works like f(f(x)).
So I wrote my code like this:
pub fn func_n<T, F: FnMut(T)> -> T>(n: u8, mut f: F) -> impl FnMut(T) -> T {
let mut g = |x| x;
for _ in 0..n {
g = |x| g(f(x));
}
g
}
And the mismatched type error occured: it says that no two closures have the same type. The compiler suggests me to box the closure, but I don't want to do that, so I can use func_n
as function directly.
I tried recursive function version too, but it occurred the same error.
So,
- Is it possible to do?
- If it is possible, how should I do?