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

相关推荐
也许明天y几秒前
Spring AI 核心原理解析:基于 1.1.4 版本拆解底层架构
java·后端·spring
舒一笑4 分钟前
一文讲透 Temporal:为什么大厂都在用它做 AI 与分布式系统的“流程大脑”?
后端·程序员·llm
Elastic 中国社区官方博客12 分钟前
在 Elastic 中使用 OpenTelemetry 内容包可视化 OpenTelemetry 数据
大数据·开发语言·数据库·elasticsearch·搜索引擎
C+++Python14 分钟前
如何学习Python的应用领域知识?
开发语言·python·学习
疯狂打码的少年17 分钟前
【Day12 Java转Python】Python工程的“骨架”——模块、包与__name__
java·开发语言·python
希望永不加班21 分钟前
SpringBoot 自定义 Starter:从零开发一个私有 Starter
java·spring boot·后端·spring·mybatis
全栈开发圈26 分钟前
新书速览|MATLAB数据分析与可视化实践:视频教学版
开发语言·matlab·数据分析
网域小星球32 分钟前
C 语言从 0 入门(二十二)|内存四区:栈、堆、全局、常量区深度解析
c语言·开发语言
止语Lab37 分钟前
Go 内存管理优化:内联是逃逸分析的隐藏杠杆
golang
悟空码字39 分钟前
别再System.out了!这份SpringBoot日志优雅指南,让你告别日志混乱
java·spring boot·后端