How to call functions by reference/pointer stored in an array?

I want to create an array (or similar) with references (or pointer) to functions and I want to be able to call a function by indexing the array. e.g like this example


should call the function that is referenced at the 5th index of foo with bar as parameter.

Is that possible in Rust?



fn foo1() {}
fn foo2() {}
fn foo3() {}
fn foo4() {} 
fn foo5() {}
fn foo6() {}

let my_funcs: &[fn()] = &[foo1, foo2, foo3, foo4, foo5, foo6];


But do note some restrictions:
All of the functions in the array must be of the same type, meaning same return type and same parameters.
This can only work for non capturing closures and bare functions like above.

For further reading:

With Box<dyn Fn()> you can store capturing closures, too (at the cost of heap-allocating their context).

Thanks. I expected these restrictions.

Just to make sure: how should it look in case of parameters and return values?

something like this?

fn foo1(x: i32, y: i32) -> i32 {}
fn foo2(x: i32, y: i32) -> i32 {}
fn foo3(x: i32, y: i32) -> i32 {}
fn foo4(x: i32, y: i32) -> i32 {} 
fn foo5(x: i32, y: i32) -> i32 {}
fn foo6(x: i32, y: i32) -> i32 {}

let my_funcs: &[fn(i32, i32) -> i32] = &[foo1, foo2, foo3, foo4, foo5, foo6];

let ret_val = (my_funcs[5])(3,2);
1 Like

Yes, like that

1 Like

Great, thanks

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.