How to put function into array?

fn test(c: usize){
fn test1(c:usize){

let a = (test, test1);
a.0(1);  //=> test
a.1(2); //=> test1

below code compile error, how to write it?

fn test<T>(c: T)->bool{
fn test1<T>(c:T)->i32{
let a =(test, test1);    // compile error

for above, I think maybe I should create a common trait for those functions so that put them together into array,

//of course below code compile error, 
//whether we can have such code for a list of functions having them togther in a arrary ? 
//whether we can impl trait for a function ?

trait FuncTrait {}
impl Functrait for test{}
impl Functrait for test1{}
let a: (dyn Functrait) = (test, test1);

What the best approach, if any, for doing this is, depends a bit on how you want to use this “array” (which in your code is actually a tuple) after creating it. In general, Rust doesn’t directly offer any way of storing a generic function (in its generic form), but traits can be used to achieve similar results; also, if you’re really trying to create some form of array (or e.g. a Vec, etc…) instead of a tuple/pair eventually, then the functions having different signatures might be hard to work with. If you’re only interested in calling the function non-generically for some fixed type (e.g. usize) in place of <T> then you can create such a function value using the “turbofish” syntax, test::<usize>

1 Like

thanks so much for your information, Steffahn,

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.