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循环中的每个循环变量, 每轮循环都是都是使用新的变量.

相关推荐
feixing_fx1 小时前
第一个 JS 程序:在浏览器控制台和 Node 中分别运行
开发语言·前端·javascript·前端框架·ecmascript
Evand J2 小时前
【MATLAB例程】二维IMM-UKF定位,基于四个基站的AOA与测距辅助
开发语言·matlab
码事漫谈2 小时前
# 2027年,AI终于要开始“干活”了
后端
feixing_fx3 小时前
变量与声明:let、const、var 的选择边界
开发语言·前端·javascript·前端框架
小满zs3 小时前
Go语言第二十一章(Gin上传文件)
后端·go
个 人 练 习 生3 小时前
C++:从零基础到深入了解vector的使用
开发语言·c++·经验分享·学习·程序人生·stl
H.莓飛4 小时前
【C++】【STL】stack_OJ题
服务器·c语言·开发语言·数据结构·c++·算法·visual studio
hudd6684 小时前
JavaEE 初阶 - 文件操作和IO
java·开发语言·java-ee
JavaGuide5 小时前
Cloudflare 开源的这套神级安全审计 Skill 太好用了!
前端·后端
学长毕设5 小时前
基于SpringBoot社区快递驿站物流配送系统-附源码
java·spring boot·后端