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!
CodePudding user response:
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
}
}
];
}
CodePudding user response:
Just to supplement the answer:
There are two ways to construct a function pointer, one is constructing via an existing function, and the other is using a closure(anonymous function) that doesn't capture any environmental variables
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);