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

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料