Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
            }
        }
    ];
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading