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 , "
") }
callback_bound := func() { print("callback_bound: " , x , y , "
") }
callback_hacked := func() { print("callback_hacked: " , "old x " , "old y" , "
") }
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
For example,
package main
func callbackXY(x, y string) func() {
return func() { print("callbackXY: ", x, y, "
") }
}
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, "
") }
}
x, y = "new x ", "new y"
callback()
}
Output:
callbackXY: old x old y
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