duanju6788 2016-04-01 02:20
浏览 251
已采纳

结构成员的Golang函数指针

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

  • 写回答

3条回答 默认 最新

  • doujilou3903 2016-04-01 03:44
    关注

    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
    ", 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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?