Skip to content

Instantly share code, notes, and snippets.

@koblas
Created September 13, 2021 20:20
Show Gist options
  • Save koblas/0d94a62d88034bcd7a64b470f62c58ce to your computer and use it in GitHub Desktop.
Save koblas/0d94a62d88034bcd7a64b470f62c58ce to your computer and use it in GitHub Desktop.
Sample Generic Summer
package main
import "fmt"
type Number interface {
type int, float32
}
func sum[T any, V Number](items []T, getvalue func(T) V) V {
var acc V
for _, item := range items {
acc += getvalue(item)
}
return acc;
}
type Payment = struct{
Id string
Amount int
Gross float32
}
func main() {
payments := []Payment{
{ "one", 1, 11 },
{ "two", 2, 22 },
{ "three", 3, 33 },
}
fmt.Println("Amount", sum(payments, func (item Payment) int { return item.Amount }))
fmt.Println("Gross", sum(payments, func (item Payment) float32 { return item.Gross }))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment