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

相关推荐
消费知多少2 分钟前
解析勤策签约大西洋焊接费用核销实践案例
开发语言·c#
马可家的菠萝18 分钟前
收藏不是终点:一个真正有用的个人知识库,至少要完成“收集 → 理解 → 行动”
前端·后端·架构
东小西29 分钟前
【SAA实战】第 2 篇:模型与消息——ReactAgent 怎么挑模型、怎么传消息
java·后端·spring
LabVIEW开发33 分钟前
LabVIEW按段拆分TDMS文件的格式边界与重构
开发语言·数据库·重构·labview·labview知识·labview功能·labview程序
qo_tn36 分钟前
Docker_02-容器操作_11-怎样进入容器执行命令
后端
架构精进之路39 分钟前
Claude Code 深度使用指南:从"会用"到"用好"的7个进阶心法
后端·openai·ai编程
明月_清风44 分钟前
看完 DSH 文档后,我总结了这 7 个关键点
前端·后端·deepseek
元界metalite44 分钟前
Spring-MVC微服务接口怎么分层-网关Controller与Service边界
后端
asdzx671 小时前
使用 Python 为 Excel 添加各类数据验证规则
开发语言·python·excel
Romantic_love_1 小时前
理解USART真实收发过程
开发语言·stm32·单片机·学习