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

I’m trying to instantiate an instance of a struct (Struct1) in an array. Instances of Struct1 store a function (method) that takes a generic type T for a parameter. The following code is how I attempted to do this:

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
            }
        }
    ];
}

But I get the error following errors:

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`.

I’m assuming the second error listed is present simply because the instance’s method wasn’t properly instantiated, because of the first listed error. But I can’t figure out what the first error is trying to say. As far as I know, Rust instantiations can be implicitly typed. I can’t figure out what else might be the problem though. Could you guys help me out with this one? Much appreciated!

>Solution :

The syntax to create an anonymous function (a closure) in Rust is not what you tried. Rather, it is:

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

Where body can be any expression, including a block (|| { body }), parameters can have type annotations (|arg: Type| {}) and the closure may specify the return type explicitly using ->: || -> ReturnType {}.

In your example,

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

Leave a Reply