如何将函数作为结构体中的成员

aso*_*sky 6 struct rust

如何在结构定义中指定函数?像这样的东西:

struct Operation {
    params: Vec<String>,
    ops: Function<Vec<String>> -> Vec<String>,
}
Run Code Online (Sandbox Code Playgroud)

我知道语法Function<Vec<String>> -> Vec<String>不正确,但我试图指定“Operation”有一个名为 that 的字段,ops它是一个接受 aVec<String>并返回 a 的闭包Vec<String>

Frx*_*rem 7

您可以用来存储任意函数:Box<dyn Fn(ArgType) -> RetType>

struct Operation {
    params: Vec<String>,
    ops: Box<dyn Fn(Vec<String>) -> Vec<String>>,
}
Run Code Online (Sandbox Code Playgroud)

一般来说,Fn特征(与FnOnce和 一起FnMut)可用于任何具有给定函数签名的可调用值,例如函数或闭包。

要创建Box<dyn Fn...>值,请使用以下内容包装任何可调用值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())
Run Code Online (Sandbox Code Playgroud)

  • 注意: `(obj.ops)(Vec::new())` 需要 rust 1.35 stable (3认同)