dqphg40600 2017-07-01 12:59
浏览 40
已采纳

Golang切片问题

I'm currently looping over a slice and removing the first element each time.

To do so, I am using the following code:

mySlice = append(mySlice[1:])

Everything goes fine for the first few iterations, but on later ones, some elements get removed and some get duplicated:

Before:

40.917
37.6384
41.2783
38.1481

After:

40.917
37.6384
41.2783
37.6384
41.2783
38.1481

I printed the len and cap of the slice for all iterations, but they seem to be decrementing by 1 for each iteration as expected.

UPDATE:

I figured out the problem: It seems that even though I am simply passing my slice to another function to create a local slice, if I manipulate the local slice, my original slice gets affected as well (D'oh!).

Go Playground Link: https://play.golang.org/p/ca57tgusXD

  • 写回答

1条回答 默认 最新

  • douban5644 2017-07-01 13:32
    关注

    I finally figured it out!

    I needed to use the copy function instead of initializing my local slices using :=.

    Go Playground Link: https://play.golang.org/p/N9RzHOibdI

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

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址