dpruwm6206 2015-01-24 00:19
浏览 15
已采纳

将结构实例上的方法作为参数传递

I have a function that accepts a function as a parameter:

func send(n int, c func(x int) int) int {
    return c(n)
}

and I have a structure with a method defined on it

type data struct {
    value int
}

func (t *data) set(x int) {
    t.value = x
}

I would like to create an instance of the structure and pass method set bound to this instance to the send function as the second parameter, to set the value field from send.

Is this possible?

https://play.golang.org/p/bv1JevQBcq

  • 写回答

1条回答 默认 最新

  • du42561 2015-01-24 00:32
    关注

    You can use a method value. Here's something similar to your example:

    package main
    
    import "fmt"
    
    func send(n int, c func(x int)) {
        c(n)
    }
    
    type data struct {
        value int
    }
    
    func (t *data) set(x int) {
        t.value = x
    }
    
    func main() {
        d := data{1}
        fmt.Println(d)
        send(2, d.set)
        fmt.Println(d)
    }
    

    playground example

    I could not use the types in the question because the function argument to send returns a value and the method does not. If you do need to use the types in the question, then use an anonymous function to adapt the method to the function argument type:

     send(2, func(v int) int { d.set(v); return 0 })
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 iOS开发关于快捷指令截屏后如何将截屏(或从截屏中提取出的文本)回传给本应用并打开指定页面
  • ¥15 unity连接Sqlserver
  • ¥15 图中这种约束条件lingo该怎么表示出来
  • ¥15 VSCode里的Prettier如何实现等式赋值后的对齐效果?
  • ¥15 流式socket文件传输答疑
  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
  • ¥50 关于多次提交POST数据后,无法获取到POST数据参数的问题
  • ¥15 win10,这种情况怎么办
  • ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式?(相关搜索:格式化)
  • ¥100 在连接内网VPN时,如何同时保持互联网连接