Given the following types :
type A struct {
...
}
func (a *A) Process() {
...
}
I would like to pass the method process
of the type A
to another function and be able to access the content of the underlying instance of A
.
How should i pass the method to another function? Via a pointer? And how should it be called ?
The Process()
method won't modify the instance of A
, i am using a pointer on the method receiver because the struct is quite large. The idea behind my question is to avoid declaring the function Process()
outside the struct and pass a ton of arguments to it (instead it access to the members of the struct).
You can even do it directly, without an interface:
package main
import "fmt"
type A struct {
Name string
}
func (a *A) Go() {
fmt.Printf("GO: %v\n", a)
}
func Test(fn func()) {
fn()
}
func main() {
aa := &A{Name: "FOO"}
bb := (*A)(nil)
cc := &A{}
Test(aa.Go)
Test(bb.Go)
Test(cc.Go)
}
Output:
GO: &{FOO}
GO: <nil>
GO: &{}
On the playground: https://play.golang.org/p/V-q2_zwX8h
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