Initialising a function pointer inside a struct


Keywords:rust 


Question: 

I've a struct that contains a function pointer

struct A {
    b: fn() -> bool,
}

fn main() {
    fn x() -> bool {
        true
    }
    let a = A { b: x };
    println!("{}", (a.b)())
}

The above snippet compiles and works as expected. Now, I am trying to avoid the defining the function seperately and do it inline in struct definition. Something like this,

struct A{
    b: fn() -> bool
}

fn main(){
    let a = A { b: fn x() -> bool { true } };
    println!("{}", (a.b)())
}

The above code doesn't compile.

Of course, it works with closures

struct A {
    b: fn() -> bool,
}

fn main() {
    let a = A { b: || true };
    println!("{}", (a.b)())
}

Question 1) Is there a way for me to assign function directly to a struct field without defining it seperately(inline).

Question 2) Functions are similar to Closures. If there are no captures, they are identical for all practical purposes. Is it safe/optimal to do this (define closures instead of functions) for struct initialisations?

Playground link


1 Answer: 

Question 1) Is there a way for me to assign function directly to a struct field without defining it separately (inline).

No.

Functions are items, items need be defined separately from their usage.

Question 2) Functions are similar to Closures. If there are no captures, they are identical for all practical purposes. Is it safe/optimal to do this (define closures instead of functions) for struct initialization?

Yes.

I would even go so far as to say that this is the idiomatic way of using closures: you rarely need to assign them a name before using them.

And if your closure accidentally captures, then it cannot be implicitly transformed into a fn and the compiler will error out.