欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

golang for循环时修改自身的值

程序员文章站 2024-02-18 13:40:22
...

一、尝试 v.Name 直接修改

1、代码

package main

import "fmt"

type User struct {
	Name string
}

func main() {
	users := []User{{Name: "姓名1"}, {Name: "姓名2"}, {Name: "姓名3"}}
	for _, v := range users {
		v.Name = "暂无"
	}
	fmt.Println(users)
}

2、打印

[{姓名1} {姓名2} {姓名3}]

Process finished with exit code 0

3、结论

  • 修改失败

二、println() 函数查看内存地址是否一致

1、代码

package main

type User struct {
	Name string
}

func main() {
	users := []User{{Name: "姓名1"}, {Name: "姓名2"}, {Name: "姓名3"}}
	for k, v := range users {
		println(&users[k], " VS ", &v)
	}
}

2、打印

0xc00003bf48  VS  0xc00003bf38
0xc00003bf58  VS  0xc00003bf38
0xc00003bf68  VS  0xc00003bf38

Process finished with exit code 0

3、结论

  • 内存地址不一样,修改无效

三、users[k].Name 修改

1、代码

package main

import "fmt"

type User struct {
	Name string
}

func main() {
	users := []User{{Name: "姓名1"}, {Name: "姓名2"}, {Name: "姓名3"}}
	for k := range users {
		users[k].Name = "暂无"
	}
	fmt.Println(users)
}

2、打印

[{暂无} {暂无} {暂无}]

Process finished with exit code 0

3、结论

  • 修改成功