Go 中捕获的闭包(用于循环变量) [英] Captured Closure (for Loop Variable) in Go

查看:24
本文介绍了Go 中捕获的闭包(用于循环变量)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Go 编译器不应该将 for...range 循环变量捕获为本地分配的闭包变量吗?

长版:

这让我在 在 C# 中有些困惑我也试图理解它;这就是为什么它在 C# 5.0 foreach 中被修复的原因(原因:循环变量不能在循环体内改变)以及在 C# 中没有修复它的原因for 循环(原因:循环变量可以在循环体内改变).

现在(对我而言)Go 中的 for...range 循环看起来很像 C# 中的 foreach 循环,但尽管事实上我们不能改变这些变量(如 kvfor k, v := range m { ... });我们仍然必须先将它们复制到一些本地闭包中,以便它们按预期运行.

这背后的原因是什么?(我怀疑这是因为 Go 以相同的方式处理任何 for 循环;但我不确定).

这里有一些代码来检查描述的行为:

func main() {lab1()//捕获的闭包不是预期的fmt.Println(" ")lab2()//捕获的闭包不是预期的fmt.Println(" ")lab3()//捕获的闭包行为正常fmt.Println(" ")}功能实验室3(){m := make(map[int32]int32)var i int32对于 i = 1;我<= 10;我++ {m[i] = i}l := [](func() (int32, int32)){}对于 k, v := 范围 m {kLocal, vLocal := k, v//(C) 捕获分配给 k 和 v 的正确值l = append(l, func() (int32, int32) {返回 kLocal,vLocal})}对于 _, x := 范围 l {k, v := x()fmt.Println(k, v)}}功能实验室2(){m := make(map[int32]int32)var i int32对于 i = 1;我<= 10;我++ {m[i] = i}l := [](func() (int32, int32)){}对于 k, v := 范围 m {l = append(l, func() (int32, int32) {kLocal, vLocal := k, v//(B) 只捕获分配给范围内 k 和 v 的最后一个值返回 kLocal,vLocal})}对于 _, x := 范围 l {k, v := x()fmt.Println(k, v)}}功能实验室1(){m := make(map[int32]int32)var i int32对于 i = 1;我<= 10;我++ {m[i] = i}l := [](func() (int32, int32)){}对于 k, v := 范围 m {l = append(l, func() (int32, int32) { return k, v })//(A) 只捕获分配给范围内 k 和 v 的最后一个值}对于 _, x := 范围 l {k, v := x()fmt.Println(k, v)}}

正如在lab1 中所示,在注释//(A) 处,我们只获得range 中的最后一个值;输出就像打印 9,9 十次,而不是像 1,12,2、...(和当然地图不一定在 Go 中排序,所以我们可能会看到 3,3 十次作为最后一对值;而不是 10,10 十次作为最后一对值值对).lab2 注释 //(B) 处的代码也是如此,这是意料之中的,因为我们试图捕获内部作用域内的外部变量(我也把这个只是为了尝试).在 lab3 的代码注释 //(C) 中,一切正常,您将在那里看到十对数字,例如 1,1, <代码>2,2, ....

我试图使用 closure+function 来替代 Go 中的 tuple.

解决方案

你想要对变量还是值进行闭包?例如,

包主导入fmt"func VariableLoop() {f := make([]func(), 3)对于我:= 0;我<3;我++ {//关闭变量 if[i] = func() {fmt.Println(i)}}fmt.Println("变量循环")对于 _, f := 范围 f {F()}}函数值循环(){f := make([]func(), 3)对于我:= 0;我<3;我++ {我 := 我//对 i 的值进行闭包f[i] = func() {fmt.Println(i)}}fmt.Println("ValueLoop")对于 _, f := 范围 f {F()}}功能变量范围(){f := make([]func(), 3)对于 i := 范围 f {//关闭变量 if[i] = func() {fmt.Println(i)}}fmt.Println("变量范围")对于 _, f := 范围 f {F()}}功能值范围(){f := make([]func(), 3)对于 i := 范围 f {我 := 我//对 i 的值进行闭包f[i] = func() {fmt.Println(i)}}fmt.Println("ValueRange")对于 _, f := 范围 f {F()}}功能主(){变量循环()值循环()变量范围()值范围()}

输出:

<前>变量循环333价值循环012可变范围222值范围012

参考文献:

<块引用>

Go 编程语言规范

函数字面量

函数字面量是闭包:它们可能引用定义在一个环绕功能.这些变量然后在围绕函数和函数文字,它们作为只要它们可以访问.

Go 常见问题解答:闭包作为 goroutine 运行会发生什么?

要在启动时将 v 的当前值绑定到每个闭包,一个必须修改内循环以在每次迭代中创建一个新变量.一种方法是将变量作为参数传递给闭包.

更简单的方法是使用声明创建一个新变量可能看起来很奇怪但在 Go 中运行良好的样式.

Shouldn't Go compiler capture for...range loop variables as a locally assigned closure variable?

Long Version:

This caused me some confusion in C# too and I was trying to understand it; that why it is fixed in C# 5.0 foreach (reason: the loop variable can not change inside the body of loop) and the reasoning for not fixing it in C# for loops (reason: the loop variable can change inside the body of loop).

Now (to me) for...range loops in Go seems pretty much like foreach loops in C#, but despite the fact that we can not alter those variables (like k and v in for k, v := range m { ... }); still we have to copy them to some local closures first, for them to behave as expected.

What is the reasoning behind this? (I suspect it's because Go treats any for loop the same way; but I'm not sure).

Here is some code to examine described behavior:

func main() {
    lab1() // captured closure is not what is expected
    fmt.Println(" ")

    lab2() // captured closure is not what is expected
    fmt.Println(" ")

    lab3() // captured closure behaves ok
    fmt.Println(" ")
}

func lab3() {
    m := make(map[int32]int32)
    var i int32
    for i = 1; i <= 10; i++ {
        m[i] = i
    }

    l := [](func() (int32, int32)){}
    for k, v := range m {
        kLocal, vLocal := k, v // (C) captures just the right values assigned to k and v
        l = append(l, func() (int32, int32) {
            return kLocal, vLocal
        })
    }

    for _, x := range l {
        k, v := x()
        fmt.Println(k, v)
    }
}

func lab2() {
    m := make(map[int32]int32)
    var i int32
    for i = 1; i <= 10; i++ {
        m[i] = i
    }

    l := [](func() (int32, int32)){}
    for k, v := range m {
        l = append(l, func() (int32, int32) {
            kLocal, vLocal := k, v // (B) captures just the last values assigned to k and v from the range
            return kLocal, vLocal
        })
    }

    for _, x := range l {
        k, v := x()
        fmt.Println(k, v)
    }
}

func lab1() {
    m := make(map[int32]int32)
    var i int32
    for i = 1; i <= 10; i++ {
        m[i] = i
    }

    l := [](func() (int32, int32)){}
    for k, v := range m {
        l = append(l, func() (int32, int32) { return k, v }) // (A) captures just the last values assigned to k and v from the range
    }

    for _, x := range l {
        k, v := x()
        fmt.Println(k, v)
    }
}

As it is shown in lab1, at the comment // (A) we get just the last values from the range; the output is like printing 9,9 ten times instead of showing expected result like 1,1, 2,2, ... (and of-course maps are not necessarily sorted in Go so we may see 3,3 ten times as the last pair of values; instead of 10,10 ten times as the last pair of values). The same goes for code at comment // (B) at lab2, which was expected because we are trying to capture outer variables inside the inner scope (I put this one too just to try that). In lab3 at code at comment // (C) everything works fine and you will see ten pairs of numbers there like 1,1, 2,2, ....

I was trying to use closure+function as a replacement for tuples in Go.

解决方案

Do you want the closure over the variable or the value? For example,

package main

import "fmt"

func VariableLoop() {
    f := make([]func(), 3)
    for i := 0; i < 3; i++ {
        // closure over variable i
        f[i] = func() {
            fmt.Println(i)
        }
    }
    fmt.Println("VariableLoop")
    for _, f := range f {
        f()
    }
}

func ValueLoop() {
    f := make([]func(), 3)
    for i := 0; i < 3; i++ {
        i := i
        // closure over value of i
        f[i] = func() {
            fmt.Println(i)
        }
    }
    fmt.Println("ValueLoop")
    for _, f := range f {
        f()
    }
}

func VariableRange() {
    f := make([]func(), 3)
    for i := range f {
        // closure over variable i
        f[i] = func() {
            fmt.Println(i)
        }
    }
    fmt.Println("VariableRange")
    for _, f := range f {
        f()
    }
}

func ValueRange() {
    f := make([]func(), 3)
    for i := range f {
        i := i
        // closure over value of i
        f[i] = func() {
            fmt.Println(i)
        }
    }
    fmt.Println("ValueRange")
    for _, f := range f {
        f()
    }
}

func main() {
    VariableLoop()
    ValueLoop()
    VariableRange()
    ValueRange()
}

Output:

VariableLoop
3
3
3
ValueLoop
0
1
2
VariableRange
2
2
2
ValueRange
0
1
2

References:

The Go Programming Language Specification

Function literals

Function literals are closures: they may refer to variables defined in a surrounding function. Those variables are then shared between the surrounding function and the function literal, and they survive as long as they are accessible.

Go FAQ: What happens with closures running as goroutines?

To bind the current value of v to each closure as it is launched, one must modify the inner loop to create a new variable each iteration. One way is to pass the variable as an argument to the closure.

Even easier is just to create a new variable, using a declaration style that may seem odd but works fine in Go.

这篇关于Go 中捕获的闭包(用于循环变量)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆