Storing functions in a vector

sample code :
https://hastebin.com/okutojedax.rb

i am trying to store functions in a vector and i am getting type error
(above code will not produce same error but problem is simlar)

expected type fn()
found type for<'r> fn(&'r mut script_functions::WorkingData) {script_functions::flush_print}

functions can have different input and output types and make changes in data via mutable references

functions can have different input and output types

How do you expect to call the functions in the vector? More precisely: what do you think the type of the T in this Vec<T> should be?

A function cannot be variadic over its arguments in Rust unless it's an extern "C" function, but that's a bit of a stretch.

What the error is telling you (At least the error you have in your main post) is that it was looking for fn() but instead found for<'r> fn(&'r mut ...) { ... } (Where I've omitted the names for now). Whenever you see this, it means that it hasn't done a cast from the function (Each function has its own type (Which is then inlined as a call to the appropriate function)) to the function pointer (Which is an address with callable code at the end).

In this specific case, I'm assuming you error occurs because you have code like the following:

fn foo() {}
fn bar() {}

let mut x = Vec::new();

x.push(foo); //Here we make x be `Vec<fn() { foo }>`
x.push(bar); //Error, `fn() { bar }` != `fn() { foo }`

You could do an explicit cast in certain cases:

let x = foo as fn();

Hence, you want to change the following line:

let mut x = Vec::new();

To the following:

let mut x: Vec<fn()> = Vec::new();

Which you've shown in your code in the example you provided, but it should compile, the error you've provided is different. Here is a fixed version. Mind you, you probably didn't test the code you posted to make sure it produced the error, which leads into my next point:

Please use the playground.

  • It's simple
  • It's fast
  • It's usable
  • It's copy/paste free
  • You can make sure your code compiles
  • It's excellent to explore errors or ideas

And... we don't end up thinking we're about to look at ruby code when we see a page ending in .rb :wink:

3 Likes

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