3

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

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"}
  // Can I do following simpler?
  ntimes(func() {obj.hello();}, 3)
}
2
  • @thesystem Edited, say is hello. What I want simplify is to eliminate anonymous function in call to ntimes. Commented Feb 25, 2013 at 1:40
  • No you can't. You could use an interface if you always knew the method you wanted to call and then just pass in the object or you can wrap the method in an anonymous function as you did in your example. Commented Feb 25, 2013 at 4:15

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.