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

相关推荐
你的人类朋友3 小时前
说说git的变基
前端·git·后端
阿杆4 小时前
玩转 Amazon ElastiCache 免费套餐:小白也能上手
后端
阿杆4 小时前
无服务器每日自动推送 B 站热门视频
后端
四维碎片4 小时前
【Qt】线程池与全局信号实现异步协作
开发语言·qt·ui·visual studio
IT码农-爱吃辣条4 小时前
Three.js 初级教程大全
开发语言·javascript·three.js
☺����5 小时前
实现自己的AI视频监控系统-第一章-视频拉流与解码2
开发语言·人工智能·python·音视频
染翰5 小时前
lua入门以及在Redis中的应用
开发语言·redis·lua
王者鳜錸5 小时前
PYTHON让繁琐的工作自动化-函数
开发语言·python·自动化
公众号_醉鱼Java5 小时前
Elasticsearch 字段膨胀使用 Flattened类型
后端·掘金·金石计划
JohnYan5 小时前
工作笔记 - CentOS7环境运行Bun应用
javascript·后端·容器