侧边栏壁纸
博主头像
Tony's Blog博主等级

行动起来,coding

  • 累计撰写 83 篇文章
  • 累计创建 58 个标签
  • 累计收到 1 条评论

目 录CONTENT

文章目录
go

go for range 踩坑

Tony
2024-02-21 / 0 评论 / 0 点赞 / 20 阅读 / 2604 字

本文链接: https://blog.csdn.net/lishuangquan1987/article/details/129102315

版权

错误的做法

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

此时model只是一个副本

正确的做法

for i, _ := range models {
			models[i].ProjectId = sql.NullInt32{Valid: true, Int32: int32(*projectId)}
			models[i].FlowId = sql.NullInt32{Valid: 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

0

评论区