1

I am trying to define a callback in golang:

package main

func main() {
    x, y := "old x ", "old y"
    callback         := func() { print("callback: "        , x        , y       , "\n") }
    callback_bound   := func() { print("callback_bound: "  , x        , y       , "\n") }
    callback_hacked  := func() { print("callback_hacked: " , "old x " , "old y" , "\n") } 

    x, y = "new x ", "new y"

    callback()
    callback_bound()
    callback_hacked()
}

The output is:

callback: new x new y
callback_bound: new x new y
callback_hacked: old x old y

The basic case works, but it leaves the variables unbound, i.e. the values at call-time are used. No doubt, this is useful in some cases, but how do I declare callback_bound so that the values at declaration-time are used and the output becomes:

callback: new x new y
callback_bound: old x old y
callback_hacked: old x old y
0

2 Answers 2

2

For example,

package main

func callbackXY(x, y string) func() {
    return func() { print("callbackXY: ", x, y, "\n") }
}

func main() {
    x, y := "old x ", "old y"
    callback := callbackXY(x, y)
    x, y = "new x ", "new y"
    callback()
}

Output:

callbackXY: old x old y

Or

package main

func main() {
    x, y := "old x ", "old y"
    callback := func() {}
    {
        x, y := x, y
        callback = func() { print("callbackXY: ", x, y, "\n") }
    }
    x, y = "new x ", "new y"
    callback()
}

Output:

callbackXY: old x old y
Sign up to request clarification or add additional context in comments.

Comments

-1
bound := func(xx,yy int) { return func(){fmt.Println(xx,yy)} }(x,y)

Untested.

Please have a look (or two) at http://golang.org/doc/effective_go.html

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.