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

相关推荐
liliangcsdn1 小时前
因子权重矩阵处理-滞回缓冲带+降频稳定化动态重选
开发语言·python·算法
ShuiShenHuoLe1 小时前
golang-jwt v5 入门
开发语言·后端·golang
码事漫谈1 小时前
DeepSeek V4.1 Flash:一次把自家旗舰送走的发布
后端
LXMXHJ1 小时前
springboot中的线程操作
java·spring boot·后端·线程
泡泡鱼(敲代码中)1 小时前
Python语法技术学习笔记
开发语言·笔记·python·学习·pycharm
Sinclair2 小时前
MCP 功能详解:内置 108 个工具,让 AI 直接帮你管理网站
后端·mcp
用户233376852182 小时前
接口卡死排查实录-缺失return的UB死循环
前端·后端
hqyjzsb2 小时前
Python 技术人转型 AI:CAIE Level I、Level II 对比怎么选
开发语言·人工智能·python·金融·数据挖掘·数据分析·aigc
用户489148799762 小时前
Go 系统服务开发实战:systemd+sdnotify + 看门狗-agent与系统服务
后端
拾光师2 小时前
Python 模式匹配:从 in 到正则再到 match-case,一招对一招
后端