golang:在回调声明中评估变量

时间:2014-03-03 00:07:02

标签: callback go

我正在尝试在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()
}

输出结果为:

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

基本情况有效,但它使变量保持未绑定状态,即使用呼叫时的值。毫无疑问,这在某些情况下很有用,但是如何声明callback_bound以便使用声明时的值并且输出变为:

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

2 个答案:

答案 0 :(得分:2)

例如,

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()
}

输出:

callbackXY: old x old y

或者

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()
}

输出:

callbackXY: old x old y

答案 1 :(得分:-1)

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

未测试。

请在http://golang.org/doc/effective_go.html

看一下(或两个)