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

相关推荐
秋91 小时前
Go语言(Golang)开发工程师全景解析:岗位职责·语言优势与使用场景·各城市薪资·发展前景·高考志愿填报(2026版)
开发语言·golang·高考
IT_陈寒1 小时前
Redis持久化这个坑,我爬了一整天才出来
前端·人工智能·后端
无风听海1 小时前
多租户系统中的 OIDC:Discovery 端点与联合登录的深度实践
后端·python·flask
小小前端仔LC2 小时前
Node.js + LangChain + React:搭建个人知识库(六)- “吃什么”项目实战:从700+菜谱入库到Taro H5端JSON渲染
前端·后端
huangdong_2 小时前
1688商品图片采集技术解析:登录态处理与SKU图自动分类
开发语言
chase_my_dream2 小时前
C++ + SLAM 高频面试问题整理
开发语言·c++·面试
程序员黑豆2 小时前
AI全栈开发之Java:怎么配置Java环境变量
前端·后端·ai编程
Cloud_Shy6182 小时前
解读《Effective Python 3rd Edition》:从练气到老魔(第五章 Item 30 - 32)
开发语言·人工智能·笔记·python·学习方法
苍何3 小时前
一手实测 Claude Fable 5,手搓了个 Obsidian 的 Codex 插件
后端
天佑木枫3 小时前
15天Python入门系列 · 序
开发语言·python