-1

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Qubasa
  • 183
  • 8
  • 3
    Showing some sample code, even if it's psuedocode or the equivalent C++, would help us understand your question. – Shepmaster Nov 11 '20 at 16:34
  • It rather sounds like you want `for (i, v) in array.iter_mut().enumerate() { *v = function(i); }` See [How to print both the index and value for every element in a Vec?](https://stackoverflow.com/q/54795989/155423); [How to iterate a Vec with the indexed position?](https://stackoverflow.com/q/28991050/155423); [Is there a way to fold with index in Rust?](https://stackoverflow.com/q/41091641/155423) – Shepmaster Nov 11 '20 at 16:36
  • Are you sure you want to generate a closure for every index ? A struct (with its method) is probably what you should use here. Or just define a trait for usize. – Denys Séguret Nov 11 '20 at 16:53

1 Answers1

1

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();
    }
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
phimuemue
  • 34,669
  • 9
  • 84
  • 115
  • 2
    This is really quite inefficient compared to `for i in 0..3 { function(i) }`, but OPs request is difficult for me to understand, so maybe it's what they want. – Shepmaster Nov 11 '20 at 16:40
  • 2
    Or maybe [this](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=a3b89626e174b5df2daa1b597914da1f), using unstable const generics... – Shepmaster Nov 11 '20 at 17:43
  • Oh I didn't know that const generics are a thing! Cool – Qubasa Nov 11 '20 at 18:22