golang 1.22特性之for loop

背景

go1.22版本 for loop每轮循环都生成新的变量.

原谅: https://tip.golang.org/doc/go1.22

Previously, the variables declared by a "for" loop were created once and updated by each iteration. In Go 1.22, each iteration of the loop creates new variables, to avoid accidental sharing bugs. The transition support tooling described in the proposal continues to work in the same way it did in Go 1.21.

测试

接下来将使用同样的代码, 分别使用go1.21.4和go1.22.4版本来运行:

go 复制代码
package main

import (
	"fmt"
	"time"
)

func main() {
	for i := 0; i < 5; i++ {
		go func() {
			fmt.Println(i, &i)
		}()
	}
	time.Sleep(time.Second)
}

在我的mac 机器上, go1.21.4的运行结果(可能每次都不太一样):

$ go run main.go
5 0x14000112008
5 0x14000112008
5 0x14000112008
3 0x14000112008
5 0x14000112008

使用go1.22.4运行的结果:

$ go run main.go
0 0x14000110018
4 0x14000110038
3 0x14000110030
1 0x14000110020
2 0x14000110028

总结

go1.22版本对于for循环中的每个循环变量, 每轮循环都是都是使用新的变量.

相关推荐
s_nshine几秒前
将 build.gradle 配置从 Groovy 迁移到 Kotlin
android·开发语言·kotlin·gradle·groovy·build
Jerry_正弦几秒前
Kotlin中object关键字的作用
android·开发语言·kotlin
wjs20245 分钟前
R 绘图 - 饼图
开发语言
buyue__5 分钟前
Kotlin/Android中执行HTTP请求
android·开发语言·kotlin
Jerry_正弦5 分钟前
Kotlin模仿Rxjava进行数据的流式转换实现
开发语言·kotlin·rxjava
向宇it12 分钟前
【unity实战】使用Unity实现动作游戏的攻击 连击 轻重攻击和打击感
开发语言·游戏·unity·游戏引擎
ZJ_.25 分钟前
Node.js 使用 gRPC:从定义到实现
java·开发语言·javascript·分布式·rpc·架构·node.js
techlead_krischang38 分钟前
中国软件评测中心最新报告:文心大模型技术、产品、应用全面领跑
后端·go
yjjpp230141 分钟前
Django REST Framework(四)DRF APIVIEW
后端·python·django