Vector of different functions

Hi,
suppose that I have two functions with different signature:

fn function_1 (arg: i32) {}

fn function_2 () -> String { String::new() }

How to put them into a vector and call them? Something like:

let functions: Vec<WHAT_TO_PUT_HERE> = vec![function_1, function_2];
functions[0](2);
let s:String = functions[1]();

Thanks

You can't. All elements in a vector need to be of the same type.

1 Like

The reason they all need to be the same type is how would you know how to call it?

A vec of an enumeration of function pointers would work, that would both let you determine 'how' to call it, makes it fully type safe, and you can encode any type in to it that you put in your enumeration.

1 Like

You can have a vector of same enums of different functions.

You can have a vector of same-type boxed closures that call different functions.

2 Likes

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