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

查看:402
本文介绍了奇怪的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 循环中,

用于...范围的 不能使用slice / array元素本身。 code>复制它循环的元素,然后附加这个临时循环变量的地址-在所有迭代中都相同。因此,您将相同的指针添加了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])
}

输出(在转到操场上尝试):

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

查看可能重复的分配的指针字段变为< nil>

pointer 类型和 non-pointer 类型,但没有 引用 (在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 s被解释为整数。

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天全站免登陆