Initializing a function pointer in a struct


#1

Is it possible to use an unnamed function to initialize a struct?

I see I can do this:

struct OpCode {    
    execute:  fn(&mut Context) -> &Context,
}

fn opc_test(ctx: &mut Context) -> &Context {
    ctx
}

static OPC_TEST: OpCode = OpCode {
    execute: opc_test
}

But oddly, I can’t seem to use an “anonymous” function:

static OPC_Test: OpCode = OpCode {
    execute: fn(ctx: &mut Context) -> &Context {
        ctx
    }
}

Or is there another syntax for this that I am missing?


#2

A fn cannot be anonymous. You can either use a named function, or you can change your struct to store a Box<Fn(&mut Context) -> &Context> trait object, which can point to either a fn or a closure.