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

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

报告相同问题?

悬赏问题

  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi