<分区>
如何在结构定义中指定函数?像这样:
struct Operation {
params: Vec<String>,
ops: Function<Vec<String>> -> Vec<String>,
}
我知道语法 Function<Vec<String>> -> Vec<String>
不正确,但我试图指定“操作”有一个名为 ops
的字段这是一个需要 Vec<String>
的闭包并返回 Vec<String>
.
<分区>
如何在结构定义中指定函数?像这样:
struct Operation {
params: Vec<String>,
ops: Function<Vec<String>> -> Vec<String>,
}
我知道语法 Function<Vec<String>> -> Vec<String>
不正确,但我试图指定“操作”有一个名为 ops
的字段这是一个需要 Vec<String>
的闭包并返回 Vec<String>
.
最佳答案
您可以使用 <a href="https://doc.rust-lang.org/nightly/std/boxed/struct.Box.html" rel="noreferrer noopener nofollow">Box</a><dyn <a href="https://doc.rust-lang.org/nightly/std/ops/trait.Fn.html" rel="noreferrer noopener nofollow">Fn</a>(ArgType) -> RetType>
存储任意函数:
struct Operation {
params: Vec<String>,
ops: Box<dyn Fn(Vec<String>) -> Vec<String>>,
}
一般来说, Fn
trait(与 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())
关于struct - 如何将函数作为结构中的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56351454/