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

相关推荐
木由里予几秒前
TEE(Trusted Execution Environment)技术详解
java·linux·开发语言·网络·嵌入式硬件·android-studio
铁皮饭盒3 分钟前
阿里ASR语音转文字,用JS模拟微信
前端·javascript·后端
计算机魔术师3 分钟前
工信部发布首部L3/L4自动驾驶系统安全要求强制性国标,2027年7月实施
人工智能·后端·自动驾驶·系统安全
程序员爱钓鱼6 分钟前
Go 数字类型详解
后端·面试·go
JckOLF04Z10 分钟前
C#客户端的异步操作
开发语言·c#
程序员爱钓鱼11 分钟前
Rust Move 详解:所有权移动与变量失效
后端·面试·rust
曹牧19 分钟前
C#:注释嵌套
开发语言·c#
snow@li22 分钟前
SpringBoot:Payload统一响应包装/全景深入梳理
java·spring boot·后端
中国搜索直付通23 分钟前
游戏车机端支付通道,会是下一个被低估的合规战场吗?
java·大数据·开发语言·人工智能·游戏
LccKyI28 分钟前
C# 零基础学习 Day01|基础概念梳理 + 思维导图总结
开发语言·笔记·学习·c#