Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang func pointer of a struct member

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).

like image 843
William Poussier Avatar asked Apr 01 '16 02:04

William Poussier


1 Answers

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

like image 177
John Weldon Avatar answered Sep 22 '22 19:09

John Weldon