6

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
  • 388,571
  • 95
  • 1,107
  • 1,366
asosnovsky
  • 2,158
  • 3
  • 24
  • 41

1 Answers1

6

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
  • 388,571
  • 95
  • 1,107
  • 1,366
Frxstrem
  • 38,761
  • 9
  • 79
  • 119