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

相关推荐
花椒技术32 分钟前
企业内部 Agent 落地复盘:Gateway、Skill 和二次确认如何串起受控业务执行
后端·agent·ai编程
我是一颗柠檬2 小时前
【MySQL全面教学】MySQL事务与ACID Day9(2026年)
数据库·后端·mysql
枕星而眠3 小时前
数据结构八大排序详解(一):四大简单排序
c语言·数据结构·c++·后端
IT_陈寒3 小时前
React useEffect闭包陷阱差点把我整失业了
前端·人工智能·后端
努力努力再努力wz3 小时前
【Qt入门系列】:按钮组件全解析:从 QAbstractButton 到快捷键事件、单选与复选机制
c语言·开发语言·数据结构·c++·git·qt·github
苍何3 小时前
爆肝两周,我把 Codex 最全实战指南开源了
后端
skywalk81633 小时前
言知(Yanzhi)系统提升建议报告和完工报告 by AutoCoder
开发语言·编程
bug菌4 小时前
【SpringBoot 3.x 第254节】夯爆了,数据库访问性能优化实战详解!
数据库·spring boot·后端
yunn_4 小时前
单例模式两种实现方法
开发语言·c++·单例模式
我材不敲代码4 小时前
Python基础:列表详解、增删改查及常用高阶操作
开发语言·windows·python