Reputation: 28
There is an array type:
const Size = 16
type idType [Size]byte
and to structure types:
type srcListItem struct {
id idType
}
type destListItem struct {
id []byte
}
I initialize source list with two items like this:
srcList := make([]srcListItem, 2)
for i := 0; i < Size; i++ {
srcList[0].id[i] = byte(i)
srcList[1].id[i] = byte(i + Size)
}
Then I try to copy it to two slices of destListItem
type. When copying one of them I use item, and to copy another index is used:
for i, item := range srcList {
fmt.Println("id slice: ", srcList[i].id)
item1 := destListItem {
id: item.id[:],
}
destList1 = append(destList1, item1)
item2 := destListItem {
id: srcList[i].id[:],
}
destList2 = append(destList2, item2)
}
the output of print result slices is:
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]}]
Tell me please why items in destList1 contains identical ids? Here is complete source code: https://play.golang.org/p/IJM5cllSb1B
Thanks.
P. S. I know some workarounds. For example the result will be correct in both cases if the source list will be of []*srcListItem
type.
But why it work so strange as is?
Upvotes: 0
Views: 64
Reputation: 10557
I believe this is a result of item
going out of scope and the for loop reusing the memory. This means that when you append item
to your slice, you hold on to it even after it "goes out of scope". When the for loop changes the memory's underlying value, you see those changes reflected in your slice.
Upvotes: 1