4

How can I specify a function in a struct definition? Something like this:

struct Operation {
    params: Vec<String>,
    ops: Function<Vec<String>> -> Vec<String>,
}

I know that the syntax Function<Vec<String>> -> Vec<String> is incorrect, but I am trying to specify that "Operation" has a field called ops that is a closure that takes a Vec<String> and returns a Vec<String>.

Shepmaster
  • 326,504
  • 69
  • 892
  • 1,159
asosnovsky
  • 1,979
  • 2
  • 22
  • 37

1 Answers1

4

You can use Box<dyn Fn(ArgType) -> RetType> to store an arbitrary function:

struct Operation {
    params: Vec<String>,
    ops: Box<dyn Fn(Vec<String>) -> Vec<String>>,
}

In general, the Fn trait (along with FnOnce and FnMut) can be used for any callable value, such as a function or a closure, that has the given function signature.

To create a Box<dyn Fn...> value, wrap any callable value with Box::new:

let obj = Operation {
    params: Vec::new(),
    // wrap a closure
    ops: Box::new(|strings| {
        /* do something... */
        strings
    }),
};

// call the function or closure inside the Box
(obj.ops)(Vec::new())
Shepmaster
  • 326,504
  • 69
  • 892
  • 1,159
Frxstrem
  • 34,562
  • 9
  • 73
  • 106