dongtan6206 2018-12-18 12:53
浏览 37
已采纳

将阵列清单复制到切片清单无法正常运作

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?

  • 写回答

1条回答 默认 最新

  • drgdn82648 2018-12-18 13:08
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?