Go:具有接收器的函数指针

huangapple go评论77阅读模式
英文:

Go: function pointer to function with receiver

问题

我可以将函数指针设置为具有接收器的函数,而不是创建一个围绕它的函数吗?

package main

import "fmt"

type hello struct {
  name string
}

func (obj *hello) hello() {
  fmt.Printf("Hello %s\n", obj.name)
}

func ntimes(action func(), n int) {
  for i := 0; i < n; i++ {
    action()
  }
}

func main() {
  obj := hello{"world"}
  // 我可以简化以下代码吗?
  ntimes(func() {obj.hello();}, 3)
}
英文:

Can I set function pointer to function with receiver simpler than creating function around it?

package main

import &quot;fmt&quot;

type hello struct {
  name string
}

func (obj *hello) hello() {
  fmt.Printf(&quot;Hello %s\n&quot;, obj.name)
}

func ntimes(action func (), n int) {
  for i := 0; i &lt; n; i++ {
    action()
  }
}

func main() {
  obj := hello{&quot;world&quot;}
  // Can I do following simpler?
  ntimes(func() {obj.hello();}, 3)
}

答案1

得分: 3

现在还不行。但是使用Go 1.1将会变得可能。Go 1.1函数调用

蓝色线接触到零时,Go 1.1将准备就绪。

英文:

Not right now. But with Go 1.1 this will be possible. Go 1.1 Function Calls

Go 1.1 will be ready when the blue line touches zero.

huangapple
  • 本文由 发表于 2013年2月25日 08:17:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/15058329.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定