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 分钟前
2025/11/5 IO流(字节流、字符流、字节缓冲流、字符缓冲流) 计算机存储规则(ASCII、GBK、Unicode)
java·开发语言·算法
手握风云-16 分钟前
Java 数据结构第二十八期:反射、枚举以及 lambda 表达式
java·开发语言
ᐇ95920 分钟前
Java Vector集合全面解析:线程安全的动态数组
java·开发语言
程序定小飞1 小时前
基于springboot的web的音乐网站开发与设计
java·前端·数据库·vue.js·spring boot·后端·spring
舒一笑1 小时前
从手写周报到智能生成:PandaCoder如何让你的工作汇报效率提升10倍
后端·程序员·intellij idea
Hello_WOAIAI1 小时前
2.4 python装饰器在 Web 框架和测试中的实战应用
开发语言·前端·python
无名之辈J1 小时前
支付常犯错误
后端
搬山.摧城1 小时前
线程池和单例模式
开发语言·单例模式
百锦再1 小时前
第1章 Rust语言概述
java·开发语言·人工智能·python·rust·go·1024程序员节
一叶之秋14121 小时前
QT背景介绍与环境搭建
开发语言·qt