go for range 踩坑

Posted lishuangquan1987

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了go for range 踩坑相关的知识,希望对你有一定的参考价值。

错误的做法

for _, model := range models 
			model.ProjectId = sql.NullInt32Valid: true, Int32: int32(*projectId)
			model.FlowId = sql.NullInt32Valid: true, Int32: int32(flow.Id)
		

此时model只是一个副本
正确的做法

for i, _ := range models 
			models[i].ProjectId = sql.NullInt32Valid: true, Int32: int32(*projectId)
			models[i].FlowId = sql.NullInt32Valid: true, Int32: int32(flow.Id)
		

测试

type Person1 struct 
	Name1 string
	Age1  int


func main() 
	persons := []Person1
		Name1: "tony1", Age1: 1,
		Name1: "tony2", Age1: 2,
		Name1: "tony3", Age1: 3,
		Name1: "tony4", Age1: 4,
	
	//打印
	fmt.Println(persons)
	//遍历修改值:错误的做法
	for i, p := range persons 
		p.Name1 = "tony"
		fmt.Println(p == persons[i])
	
	fmt.Println("错误的遍历后输出值:")
	fmt.Println(persons)
	//遍历修改值:正确的做法
	for i, _ := range persons 
		persons[i].Name1 = "tony"
	
	fmt.Println("正确的遍历后输出值:")
	fmt.Println(persons)

输出:

PS E:\\Go Project\\test20221122> go run main.go
[tony1 1 tony2 2 tony3 3 tony4 4]
false
false
false
false
错误的遍历后输出值:
[tony1 1 tony2 2 tony3 3 tony4 4]
正确的遍历后输出值:
[tony 1 tony 2 tony 3 tony 4]

可以看到:fmt.Println(p == persons[i])这一句输出的是false

以上是关于go for range 踩坑的主要内容,如果未能解决你的问题,请参考以下文章

Go“一个包含nil指针的接口不是nil接口”踩坑

Go语言自学系列 | golang for range循环

Golang 基础:Go Module, for range, 切片, map, struct 等使用和实现

Golang 基础:Go Module, for range, 切片, map, struct 等使用和实现

Golang 入门总结:Go Module, for range, 切片, map, struct 等使用和实现

Golang 入门总结:Go Module, for range, 切片, map, struct 等使用和实现