Arrays 将数组列表复制到切片列表的操作错误

Arrays 将数组列表复制到切片列表的操作错误,arrays,go,slice,Arrays,Go,Slice,有一种数组类型: const Size = 16 type idType [Size]byte 和结构类型: type srcListItem struct { id idType } type destListItem struct { id []byte } 我使用以下两项初始化源列表: srcList := make([]srcListItem, 2) for i := 0; i < Size; i++ { srcList[0].id[i] = byte(

有一种数组类型:

const Size = 16
type idType [Size]byte
和结构类型:

type srcListItem struct {
    id idType
}
type destListItem struct {
    id []byte
}
我使用以下两项初始化源列表:

srcList := make([]srcListItem, 2)
for i := 0; i < Size; i++ {
    srcList[0].id[i] = byte(i)
    srcList[1].id[i] = byte(i + Size)
}
打印结果切片的输出为:

destList1 items array:  [{[16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31]} {[16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31]}]
destList2 items array:  [{[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]} {[16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31]}]
请告诉我为什么destList1中的项目包含相同的ID? 以下是完整的源代码:

谢谢

另外,我知道一些解决办法。例如,如果源列表为
[]*srcListItem
类型,则两种情况下的结果都是正确的。
但是为什么它工作得如此奇怪呢?

我相信这是
超出范围和for循环重用内存的结果。这意味着,当您将
附加到切片时,即使在它“超出范围”后,您仍会保留它。当for循环更改内存的基本值时,您会看到这些更改反映在您的片中。

您能想出一个简单的例子吗?假设它在使用index
srcList[i]时工作正常。id[:]
,因为golang又创建了一个
srcListItem
的副本。这是预期的行为还是golang optimizer中的错误?我不认为这是错误。我想你不能指望迭代器的值通过那个迭代。@Leo这不是一个bug
srcList[i]
项在内存中不共享同一位置。您可以这样想:在每次迭代中,
range
srcList[i]
中的值复制到
item
中,在循环开始时恢复分配给
item
的内存。执行
item[:]
返回一个切片,该切片引用
item
的存储,即其内存,即分配给item的范围循环的内存,并在每次迭代中重用。
destList1 items array:  [{[16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31]} {[16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31]}]
destList2 items array:  [{[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]} {[16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31]}]