Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference to another field with in a func in the same struct in golang

Tags:

struct

go

I have a struct looks something like this:

type Job struct {
    Action  func()
    Cron    string
}

So for an instance of this struct, is it possible for the code inside the implementation of Action to get a reference to Cron? Thanks.


2 Answers

Use a closure to create the Action function:

func MakeAction(job *Job) func() {
    return func() {
        // function that uses the variable job
    }
}

You can use the MakeAction function like this:

j := &Job{ nil, "foo" }
j.Action = MakeAction(j)

Notice that this will behave in possibly unexpected ways when somebody makes a copy of the Job structure—the reference inside the closure created by MakeAction() will still point to the original instance (instead of the copy).

like image 162
fuz Avatar answered Oct 26 '25 01:10

fuz


You seem to have to pass a Job reference to the Action function in order for said function to access Cron.

See for instance:

package main

import "fmt"

type Job struct {
    Action func(*Job)
    Cron   string
}

func main() {
    j := &Job{f, "test"}
    fmt.Println("Hello, playground", j)
    j.Action(j)
}

func f(j *Job) {
    fmt.Println(j.Cron)
}

Output:

Hello, playground &{0x201a0 test}
test

None of the closures examples allows you to reference your own struct.


The OP adds:

The external framework expects a function like this: func().
I'm wrapping this function into my homebrewed struct Job, and I put something else into the Job struct.
Now I hope the Action could access other fields in Job, but it doesn't seem to be possible.
Later I will pass the Action directly into the external framework.

I confirm that, just by wrapping func() (from external framework) in a struct of yours doesn't means f has access to the struct fields through closure.
You need a separate initialization, as FUZxxl's answer shows.

Otherwise, how that function (from an external framework) would even know about Job?
That could only work if that function expect an interface with a Cron() function, not a struct which it knows nothing about, with a Cron field.
As in this example.

like image 26
VonC Avatar answered Oct 26 '25 02:10

VonC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!