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

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

Go: function pointer to function with receiver

问题

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

  1. package main
  2. import "fmt"
  3. type hello struct {
  4. name string
  5. }
  6. func (obj *hello) hello() {
  7. fmt.Printf("Hello %s\n", obj.name)
  8. }
  9. func ntimes(action func(), n int) {
  10. for i := 0; i < n; i++ {
  11. action()
  12. }
  13. }
  14. func main() {
  15. obj := hello{"world"}
  16. // 我可以简化以下代码吗?
  17. ntimes(func() {obj.hello();}, 3)
  18. }
英文:

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

  1. package main
  2. import &quot;fmt&quot;
  3. type hello struct {
  4. name string
  5. }
  6. func (obj *hello) hello() {
  7. fmt.Printf(&quot;Hello %s\n&quot;, obj.name)
  8. }
  9. func ntimes(action func (), n int) {
  10. for i := 0; i &lt; n; i++ {
  11. action()
  12. }
  13. }
  14. func main() {
  15. obj := hello{&quot;world&quot;}
  16. // Can I do following simpler?
  17. ntimes(func() {obj.hello();}, 3)
  18. }

答案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:

确定