0

I have an array:

const assets = [{
  type: 'X',
  value: 322.12
}, {
  type: 'X',
  value: 413.21
}]

皇冠hg0088代理网址I want the sum of values (735,33)

In node.js I can use: const sum = assets.reduce((s, val) => ( s = s + val.value), 0)

How can I do the same in Go?

  • 8
    Use a loop to sum the values: var s int; for _, asset := range assets { s += asset.value }. Loops are covered in the . – Muffin Top Jul 28 at 21:35
  • reduce is actually a method on js Arrays, and it didn't implement on the go arrays. Although you shouldn't expect functional language properties on go either. Go is used to be simple and in order to do such a reduce thing you have to use a simple for. But if you really insist to use that style, you can also define your own array type in go and write a reduce method for id :D – meshkati Jul 29 at 3:15
3

is an incomplete implementation, but it gives you an idea of why this is a bad idea and non-idiomatic 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))
}

Since there are no generics in Go, you'll have to create a different reducer method for every return type, which might be quite impractical.

See also .

| improve this answer | |
2

I would go with

i = 0
f = 0
for _, asset := range assets {
    integer, frac := Modf(asset.value)
    i += integer
    f += math.Round(frac*100)/100))
}
fmt.Println(i, f)
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy皇冠hg0088代理网址

Not the answer you're looking for? Browse other questions tagged or ask your own question.