如何从循环中填充可变参数

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

Howto fill variant args from a loop

问题

对于以下示例,我需要从文件中读取值(没有问题),并将其作为数据点放入方法"func (r *Regression) Train(d ...*dataPoint)"中。这样可以实现:

r.Train(
	regression.DataPoint(1, []float64{1, 1, 1}),
	regression.DataPoint(4, []float64{2, 2, 2}),
	regression.DataPoint(9, []float64{3, 3, 3}),
)

但是我想要像这样使用循环来实现:

for i := 1; i <= 4; i++ {
   ??? regression.DataPoint(i*i, []float64{i, i, i}), ???
}

我不能使用dataPoint的数组,因为它只在该包中可见。这是完整的源代码:

https://github.com/sajari/regression(查看示例用法)

非常感谢,

Maciej

英文:

for the following example I need to read values from a file (no problem) and put it into the method "func (r *Regression) Train(d ...*dataPoint)" as datapoints. This works:

r.Train(
	regression.DataPoint(1, []float64{1, 1, 1}),
	regression.DataPoint(4, []float64{2, 2, 2}),
	regression.DataPoint(9, []float64{3, 3, 3}),
)

but I would like to put it from a loop like this:

for i := 1; i &lt;= 4; i++ {
   ??? regression.DataPoint(i*i, []float64{i, i, i}), ???
}

I can not use an array of dataPoint as it is only visible in that package. Here is the full source code:

https://github.com/sajari/regression (see example usage)

Thank you very much,

Maciej

答案1

得分: 1

从你提供的链接页面上可以看到:

注意:你也可以逐个添加数据点。

因此,你需要:

for i := 1; i <= 4; i++ {
   r.Train(regression.DataPoint(i*i, []float64{i, i, i}))
}
英文:

From the page you linked:

Note: You can also add data points one by one.

Therefore you need:

for i := 1; i &lt;= 4; i++ {
   r.Train(regression.DataPoint(i*i, []float64{i, i, i}))
}

答案2

得分: 0

@Milo的答案可能适用于你的特定情况,但对于具有可变参数函数的一般情况,你可以将元素追加到切片中,然后将切片用作可变参数列表:

r.Train(points...)

不幸的是,回归库设计得不太好,因为它公开暴露了接收和返回未公开类型的函数,这样你就无法处理它们。

英文:

@Milo's answer is probably best for your particular case, but for the general case with variadic functions, you can append elements to a slice, then use the slice as the variadic argument list:

r.Train(points...)

Unfortunately the regression library is not very well-designed, as it has publicly-exposed functions that receive and return unexposed types, leaving you no way to work with them.

huangapple
  • 本文由 发表于 2017年7月26日 20:43:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/45327361.html
匿名

发表评论

匿名网友

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

确定