在 Rust 中正确编写结构的函数 属性 时遇到问题

Having trouble writing the function property of a struct correctly in Rust

我正在尝试在数组中实例化结构 (Struct1) 的实例。 Struct1 的实例存储一个函数 (method),该函数采用通用类型 T 作为参数。以下代码是我尝试执行此操作的方式:

struct Struct1<T> {
    method: fn(T)
  }
  
fn main() {
    let arrOfStructs = [
        Struct1 { 
            method: fn(char) {
                let a = char; //this does nothing useful, just a mock function
            }
        }
    ];
}

但是我得到以下错误:

error: expected expression, found keyword `fn`
 --> test.rs:8:21
  |
7 |         Struct1 {
  |         ------- while parsing this struct
8 |             method: fn(char) {
  |                     ^^ expected expression

error[E0063]: missing field `method` in initializer of `Struct1<_>`
 --> test.rs:7:9
  |
7 |         Struct1 {
  |         ^^^^^^^ missing `method`

error: aborting due to 2 previous errors

For more information about this error, try `rustc --explain E0063`.

我假设列出的第二个错误存在只是因为实例的方法没有正确实例化,因为列出的第一个错误。但我无法弄清楚第一个错误试图说什么。据我所知,Rust 实例化可以隐式类型化。我不知道还有什么问题。你们能帮我解决这个问题吗?非常感谢!

在 Rust 中创建匿名函数(闭包)的语法不是您尝试过的。相反,它是:

|arg1, arg2, arg3, ...| body

其中 body 可以是任何表达式,包括块 (|| { body }),参数可以有类型注释 (|arg: Type| {}),闭包可以指定 return使用 -> 显式键入:|| -> ReturnType {}.

在你的例子中,

fn main() {
    let arrOfStructs = [
        Struct1 { 
            method: |char: YouHaveToSpecifyTheTypeHere| {
                let a = char; //this does nothing useful, just a mock function
            }
        }
    ];
}

补充一下答案:

构造函数指针有两种方法,一种是通过已有函数构造, 另一个使用不捕获任何环境的闭包(匿名函数) 变量

fn add_one(x: usize) -> usize {
    x + 1
}

// using an existing function
let ptr: fn(usize) -> usize = add_one;
assert_eq!(ptr(5), 6);

// using a closure that does not enclose variables
let clos: fn(usize) -> usize = |x| x + 5;
assert_eq!(clos(5), 10);

link to the official doc