I have to iterate over an array and assign to every index a function with a prescribed signature. I would like to generate a function which knows its index when called.
I would use template values in C++, but this does not work in Rust.
I have to iterate over an array and assign to every index a function with a prescribed signature. I would like to generate a function which knows its index when called.
I would use template values in C++, but this does not work in Rust.
This could serve as a starting point:
fn make_fn_for_index(i: usize) -> impl Fn() -> () { // this function returns a function
move || {
// move gives ownership of captured variables to closure
println!("at index {}", i);
}
}
fn main() {
let arr_of_fns: [Box<dyn Fn() -> ()>; 3] = [
Box::new(make_fn_for_index(0)),
Box::new(make_fn_for_index(1)),
Box::new(make_fn_for_index(2)),
];
for function in arr_of_fns.iter() {
function();
}
}