go中 for循环的坑

在使用for循环修改结构体切片中的值时,发现并没有修改成功。

type Dog struct {name string}func (d *Dog) setNewName(name string) {d.name = name}func main() {d := Dog{name: "123",}d1 := Dog{name: "456",}d2 := Dog{name: "789",}dogSlice := make([]Dog, 0)dogSlice = append(dogSlice, d, d1, d2)for _, dog := range dogSlice {dog.setNewName("123")}for _, dog := range dogSlice {fmt.Println(dog)}}

结果切片中dog的name并没有全部变为123,后来查资料才知道for循环中的dog其实是个变量,指向的并不是真正的dog。

打印其地址对比可以看出压根就不同。

for i, dog := range dogSlice {fmt.Printf("dog地址:%p 切片中dog的真正地址:%p\n", &dog, &(dogSlice[i]))}dog地址:0x14000010230 切片中dog的真正地址:0x14000066180dog地址:0x14000010230 切片中dog的真正地址:0x14000066190dog地址:0x14000010230 切片中dog的真正地址:0x140000661a0

若要修改切片中的dog的name,应该按照以下这么写,或者将dogSlice变为存dog指针的切片,dogSlice := make([]*Dog, 0)

for i, _ := range dogSlice {dogSlice[i].setNewName("123")}for _, v := range dogSlice {fmt.Println(v)}打印如下:{123}{123}{123}