2014-03-03 73 views
1

我試圖定義golang回調: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_bound以便使用在聲明時間值和輸出變爲:

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

回答

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