How do I iterate through a list of function calls with different (numbers of) parameters?

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, so I'm using "sleep" as a placeholder.

My issue is that I'm unable to create a list of functions with a different number of parameters.

You can't, because you wouldn't be able to call it item.1(); just doesn't make sense semantically when item.1 takes 1 or more arguments.

Your alternatives are

  1. Try to find a common signature for all functions, for example fn(&[&str]). In that case, each function gets a slice of &str as 1 argument and has to do a length check at runtime.
  2. Use some type hackery with HList, which will result in very unreadable and unidiomatic code. See frunk::hlist - Rust.
1 Like

You will need to make a trait that can call any of them, e.g.:

trait CallableFunction {
    fn call_it(&self, args: &[&str]);
}

impl CallableFunction for fn(&str, &str) {
    fn call_it(&self, args: &[&str]) {
        (self)(args[0], args[1]);
    }
}

// etc.

and then make sure to cast function pointers to this trait (as &dyn CallableFunction), as by default they have their own unique function type.

2 Likes

If I can't I'm probably better off asking if I can iterate through a list of generated commands and call them.

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.