尝试创建 MovingAverage 类型的切片。

huangapple go评论99阅读模式
英文:

Trying to create slice of type MovingAvarage

问题

我正在使用RobinUS2/golang-moving-average库来计算移动平均值,但是我无法组装一个包含这些平均值的切片来计算多个变量的移动平均值。

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

可能出了什么问题?我得到了一个索引超出范围的错误。谢谢!

英文:

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

得分: 2

你需要在切片之前进行预分配大小,例如:

ma := make(movingaverage.MovingAverage, 5)

这将创建一个容量为5、长度为5的切片,其中每个条目都设置为零值。

更好的做法是先初始化切片,然后使用以下方式添加新条目:

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

如果你知道最终切片的大小,你可以使用以下方式预分配底层数组的大小:

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

这将创建一个长度为0、容量为5的切片,这样你就不必进行重复的内存分配和移动。

英文:

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

huangapple
  • 本文由 发表于 2017年8月19日 05:05:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/45765046.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定