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

标签 struct rust

<分区>

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

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/

相关文章:

c++ - 编写一个宏来将结构的内容字符串化

rust - 生成线程并保留其中的数据

C# 结构,使用方法处理 Bool 类型?

c - c 中结构的大小等于 1

带有引用的 Rust 泛型 AddAssign

string - 如何将 &str 转换为 &[u8]

rust - 有没有一种稳定的方法来告诉 Rustfmt 跳过整个文件

rust - 在 for 循环中推送到 Vec 时,新成员如何保持?

c - 别名结构(或将一个结构的定义粘贴到另一个结构中)

将 struct 转换为 int