gpt4 book ai didi

callback - 戈朗 : evaluate variable in callback declaration

转载 作者:IT王子 更新时间:2023-10-29 02:17:35 26 4
gpt4 key购买 nike

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

基本情况有效,但它使变量未绑定(bind),即使用调用时的值。毫无疑问,这在某些情况下很有用,但我如何声明 callback_bound 以便使用声明时的值并且输出变为:

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

最佳答案

例如,

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

关于callback - 戈朗 : evaluate variable in callback declaration,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22135486/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com