奇怪的golang“追加"行为(覆盖切片中的值) [英] Strange golang "append" behavior (overwriting values in slice)

查看:43
本文介绍了奇怪的golang“追加"行为(覆盖切片中的值)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个简单的代码:

import "fmt"

type Foo struct {
    val int
}

func main() {
    var a = make([]*Foo, 1)
    a[0] = &Foo{0}

    var b = [3]Foo{Foo{1}, Foo{2}, Foo{3}}
    for _, e := range b {
        a = append(a, &e)
    }

    for _, e := range a {
        fmt.Printf("%v ", *e)
    }
}

我原以为它会打印 {0} {1} {2} {3},但它会打印 {0} {3} {3} {3}>.这里发生了什么?

I was expecting it to print {0} {1} {2} {3}, however it prints {0} {3} {3} {3}. What happened here?

推荐答案

这是因为在 for 循环中,您使用的是 copy 而不是切片/数组元素本身.

This is because in the for loop you operate with a copy and not with the slice/array element itself.

for ... range 复制它循环的元素,然后附加这个临时循环变量的地址——这在所有迭代中都是相同的.所以你添加了 3 次相同的指针.这个临时变量将在最后一次迭代(数组的最后一个元素)中设置为 Foo{3},所以这就是为什么你看到它打印了 3 次.

The for ... range makes a copy of the elements it loops over, and you append the address of this temporary, loop variable - which is the same in all iterations. So you add the same pointer 3 times. And this temporary variable will be set to Foo{3} in the last iteration (last element of the array), so that's why you see that printed 3 times.

修正:不加循环变量的地址,而是加数组元素的地址:

Fix: do not add the address of the loop variable, but the address of the array element:

for i := range b {
    a = append(a, &b[i])
}

输出(在 Go Playground 上试试):

Output (try it on the Go Playground):

{0} {1} {2} {3} 

查看可能重复的 分配的指针字段变为 .

在 Go 中有指针类型和非指针类型,但没有"references"(意思是它在 C++ 和 Java 中使用).鉴于没有参考"的事实在 Go 中输入,这不是意外行为.循环变量只是一个普通"变量.局部变量,它只能保存一个值(可以是指针也可以是非指针),不能保存引用.

In Go there are pointer types and non-pointer types, but no "references" (in the meaning it is used in C++ and Java). Given the fact that there are no "reference" types in Go, this is not an unexpected behavior. The loop variable is just an "ordinary" local variable, it can only hold a value (which may be a pointer or non-pointer), but not a reference.

摘自这个答案:

指针是值,就像我们说 int 数字一样.不同之处在于该值的解释:指针被解释为内存地址,而 int 被解释为整数.

Pointers are values just like let's say int numbers. The difference is the interpretation of that value: pointers are interpreted as memory addresses, and ints are interpreted as integer numbers.

当你想改变一个 int 类型的变量的值时,你传递一个指向 int 的指针,它的类型是 *int>,然后修改指向的对象:*i = newvalue(分配的值是 int).

When you want to change the value of a variable of type int, you pass a pointer to that int which is of type *int, and you modify the pointed object: *i = newvalue (the value assigned is an int).

指针也是一样:当你想改变一个指针类型*int的变量的值时,你传递一个指向那个*int的指针,它的类型是**int 并修改指向的对象:*i = &newvalue(分配的值是 *int).

Same goes with pointers: when you want to change the value of a variable of pointer type *int, you pass a pointer to that *int which is of type **int and you modify the pointed object: *i = &newvalue (the value assigned is an *int).

总而言之,循环变量只是一个普通变量,它具有您要循环的数组/切片的元素类型,并且要使其具有实际迭代的值,必须为其分配该值复制值.它会在下一次迭代中被覆盖.

All in all, the loop variable is just a normal variable having the element type of the array/slice you're looping over, and for it to have the value of the actual iteration, the value must be assigned to it which copies the value. It is overwritten in the next iteration.

这篇关于奇怪的golang“追加"行为(覆盖切片中的值)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆