我有一个数组:
const assets = [{
type: 'X',
value: 322.12
}, {
type: 'X',
value: 413.21
}]
我想要值的总和(735,33)在node.js中,我可以使用:
const sum = assets.reduce((s, val) => ( s = s + val.value), 0)
如何在Go中执行相同的操作?
最佳答案
Here是一个不完整的实现,但是它使您了解为什么这是一个不好的主意和非惯用的Go:
package main
import "fmt"
type Array []int
type ReducerFn func(prev int, next int) int
func (arr Array) Reduce(fn ReducerFn, i int) int {
prev := i
for _, v := range arr {
prev = fn(prev, v)
}
return prev
}
func main() {
i := Array([]int{1,2,4})
fmt.Println(i.Reduce(func(prev int, next int) int {
return prev + next
}, 10))
}
由于Go中没有泛型,因此您必须为每种返回类型创建不同的reducer方法,这可能是不切实际的。另请参见Francesc Campoy's talk at dotGo2015, "Functional Go?"。
关于arrays - 数组精简或类似,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63143120/