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.
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).
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 structJob, and I put something else into theJobstruct.
Now I hope theActioncould access other fields inJob, but it doesn't seem to be possible.
Later I will pass theActiondirectly 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With