I need to write a Rust function that can modify state defined in a higher function and propagate it from one function call to another in an iterator (see the pseudo-code below).
In bad C, I would do it using a shared pointer. Of course, I understand why I should not do that, and why I can not do it in Rust.
The workaround I found is to add an extra function parameter and an additional return argument:
fn f(inputs ..., s) {
let mut s = s;
// computations that rely on the value of s
// ...
outputs ..., s
}
fn main() {
let mut s;
for ... {
let (outputs ..., x) = f(inputs ..., s);
s = x;
}
}
This seems a bit heavy in terms of programming style and I hope that there is a lighter construction (maybe more monadic), I imagine using closures. How I should write it is not obvious to me.