pointers - 循环中覆盖的封闭变量

标签 pointers go

我正在尝试构建一个包含封闭变量(在本例中为字符串)的函数数组,但我得到了一些意外的输出。我认为我得到此输出的原因是因为附加的 func 文字实际上是指向代码的指针,该代码在每次迭代后都会更改。

有没有办法new()make()一个函数类型,这样append()会得到一个不同的函数实例改为每次迭代?

package main

import "log"

var functions []func()

func main() {
    for _, s := range [...]string{"goodbye", "cruel", "world"} {
        functions = append(functions, func() {
            log.Println(s)
        })
    }
    for _, f := range functions {
        f()
    }
}

输出:

2014/11/23 18:13:16 world
2014/11/23 18:13:16 world
2014/11/23 18:13:16 world

最佳答案

循环的每次迭代都使用变量 s 的相同实例,因此每个闭包共享该单个变量。要在启动时将 s 的当前值绑定(bind)到每个闭包,必须修改内部循环以在每次迭代时创建一个新变量。例如,

package main

import "log"

var functions []func()

func main() {
    for _, s := range [...]string{"goodbye", "cruel", "world"} {
        s := s // create new s
        functions = append(functions, func() {
            log.Println(s)
        })
    }
    for _, f := range functions {
        f()
    }
}

输出:

2009/11/10 23:00:00 goodbye
2009/11/10 23:00:00 cruel
2009/11/10 23:00:00 world

引用资料:

What happens with closures running as goroutines?

Captured Closure (for Loop Variable) in Go

关于pointers - 循环中覆盖的封闭变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27096978/

相关文章:

C++:为什么取消引用此 vector 迭代器段错误?

html - 为什么我的 go-code 不适用于每个模板?

json - 在 Golang 中读取请求体两次

正则表达式 "is not a constant"编译错误

unit-testing - GoLang Sarama ConsumerGroup模拟

c# - Protobuf 解码任意消息。 Protobuf 消息多态性

c - 将指针传递给指针数组作为参数

c - char* 和 int* 之间的取消引用运算符 (*) 差异

c - 如何在 C 中将常量 char 指针转换为小写?

pointers - 调用结构函数给出 "cannot refer to unexported field or method"