How do I iterate through a list of function calls?

Rust Playground

I'm trying to create a list of functions,
calling them and see how far I am progressing.

It's actually probably supposed to be a list of copy commands,
but I haven't gotten that far as of yet.

My issue is that I have no idea how calling functions work.
Why is there an Fn(), FnMut() and FnOnce().
Why don't I know the size of a function at compile-time?
Isn't is just a name of a function I'm storing?
Can I use a slice since I will probably be able to calculate the amount of commands/copies
I will call before I call the install.handle() function or is it advisable to use a vector and why?

  • The Fn trait is for functions that can be called multiple times with only immutable access to the function object.
  • The FnMut trait is for functions that can be called multiple times with mutable access to the function object.
  • The FnOnce trait is for functions that can only be called once.

The Fn traits encompass more things than just function pointers. If you wanted a function pointer, then the type is called fn() with a lower-case f, and it will work if you change dyn Fn() to fn() everywhere.

To see what other things can implement the Fn traits, see Closures: Anonymous Functions that Capture Their Environment. This chapter explains how closures can hold on to local variables next to where they are defined. The local variable will become part of the closure, so the size of the closure will depend on what local variables it captures.

You don't know the size because it could capture many different variables of different size.

To use the Fn trait, you should use a Box like this: Box<dyn Fn()>. full example

If you use a slice, then you're saying "the actual data is stored outside of the Installation struct", and you have to define some other place to actually own the data. That doesn't sound like what you want, so you should use a vector (or array).

Similarly, you probably want a String rather than &str. With a &str, you're saying that the string data is actually stored outside of the Installation struct. In this case, it works because all of the strings are compile-time constants, but if you ever want to store strings that are not compile-time constants then it won't work.

(With compile-time constant strings, the actual string data is stored in an immutable global variable generated by the compiler.)

7 Likes

I'm so far looking for the fn() type and was distracted by the similar name that seems encompass more than just a function (closures that include variables?).

And thank you for explaining it all.
I might need the other in the future.