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

相关推荐
带娃的IT创业者几秒前
深度解析:从零构建高性能 LLM API 中转网关与成本优化实战
开发语言·gpt·llm·php·高性能·成本优化·api网关
TechWayfarer12 分钟前
IP归属地运营商能解决什么问题?风控/增长/数据平台落地实践(附API代码)
开发语言·网络·python·网络协议·tcp/ip
Nyarlathotep011321 分钟前
JUC工具(3):StampedLock的基础和原理
java·后端
Alice-YUE30 分钟前
【JS高频八股】什么是闭包?
开发语言·javascript·笔记·学习
微学AI30 分钟前
Claude-Code-python 前端改造项目工作流程详解
开发语言·前端·python
乐世东方客40 分钟前
Nacos-2.1.0问题-自己记录
开发语言·python
直奔標竿1 小时前
Java开发者AI转型第二十二课!Spring AI 个人知识库实战(一)——架构搭建与核心契约落地
java·人工智能·后端·spring·架构
清汤饺子1 小时前
【译】我的 AI 进阶之路:从怀疑到深度整合
前端·javascript·后端
亿牛云爬虫专家1 小时前
Go爬虫进阶:如何优雅地在Colly框架中实现无缝代理切换?
爬虫·中间件·golang·爬虫代理·colly框架·代理切换·api提取
每天吃饭的羊1 小时前
UMD和IIfe
开发语言·前端·javascript