#Closure with variable number of arguments

8 messages · Page 1 of 1 (latest)

scarlet notch
#

I have a struct that I want to look a bit like the following:

struct C {
  arg_1: Option<A>,
  arg_2: Option<B>,
  caller: FnMut[...]
}

The caller is supposed to be a closure which can have either arguments

  • |x| if both arg_1 and arg_2 are None
  • |x, a/b| depending whether arg_1 or arg_2 are Some with all three arguments if neither are None. Currently looking at this as part of a builder problem - is this possible? If yes, how would that look like?
outer yoke
#

it is not possible to store all those different functions in one field

#

however, if your goal is "in the future, call the function with these arguments" then you can do that by storing a boxed closure with zero arguments, that captures the arguments and the function

scarlet notch
#

Okay, I see. I still had an idea to implement a marker trait but that’s then still not gonna achieve what I wanted to. Might fall back to several structs then…
There’s also no macro magic with which I could overengineer this, right?

outer yoke
#

you could define an enum where each variant is a function and the right number of arguments; if you did that, you would have to implement the function call code for each variant separately

#
enum C {
    Zero(Box<dyn FnMut(X)>),
    A(Box<dyn FnMut(X, A)>, A),
    B(Box<dyn FnMut(X, B)>, B),
    AB(Box<dyn FnMut(X, A, B)>, A, B),
}
#

(or &dyn or whatever flavor of FnMut container you actually need)

scarlet notch
#

Ah, okay… I can try that route 🙂