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.

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

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题