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 小时前
路由注册:RouterGroup(routergroup.go)
开发语言·后端·golang
小当家.1053 小时前
LLM服务缓存与连接池管理:三层缓存架构与ChatClient池化
java·后端·spring·缓存·llm·agent
Darkwanderor3 小时前
C++的流简介和简单使用
开发语言·c++
人间凡尔赛3 小时前
当 AI Agent 攻陷网关:Istio agentgateway 与 Gateway API Inference Extension 实战解析
后端·云原生·架构
北冥you鱼3 小时前
深入解析 Go 中 sync.YAML.Unmarshal:如何将 YAML 数据填充到 Config 结构体
开发语言·算法·golang
wwwzhouzy3 小时前
SpringBoot 响应式编程
java·spring boot·后端·响应式编程
Python私教3 小时前
请求超时不等于失败:把写操作恢复设计成事实回读
后端·python
goldbin_zhang_xu3 小时前
我用 Go 重写了一个 OpenClaw 框架:这就是 GoClaw
开发语言·后端·golang·agent框架·goclaw·双循环机制
IT_陈寒3 小时前
Redis的KEYS命令差点把我的生产环境拖垮,改用SCAN吧
前端·人工智能·后端
lingran__3 小时前
C++ STL map 与 set 底层剖析与模拟实现万字详解|基于红黑树,复刻 SGI-STL 泛型复用架构
开发语言·c++·stl·set·map·泛型编程·sgi-stl