duanban4769 2017-08-18 21:05
浏览 16
已采纳

尝试创建类型为MovingAvarage的切片

I am using the RobinUS2/golang-moving-average library to compute moving avarages, but I am unable to assembe a slice of these avarages to compute MA for multiple variables.

ma := []movingaverage.MovingAverage{}
    ma[0] = movingaverage.New(15)
    ma[0].Add(3.14)

What could be wrong? I get an index out of range error. Thanks!

  • 写回答

1条回答 默认 最新

  • duanmu6231 2017-08-18 21:16
    关注

    You need to either pre-size the slice with

    ma := make(movingaverage.MovingAverage, 5)
    

    Which gives a slice of capacity 5 and length 5 with each entry set to the zero value

    Better though to initialise it as you did but then to add new entries with

    ma = append(ma, movingaverage.New(15)) 
    

    If you know how big your eventual slice will be you can pre-allocate the underlying array with

    ma := make(movingaverage.MovingAverage, 0, 5)
    

    which will give you a slice of length 0 but capacity 5 so you don't have to do repeated memory allocations and moves

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

报告相同问题?

悬赏问题

  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)