Created
September 13, 2021 20:20
-
-
Save koblas/0d94a62d88034bcd7a64b470f62c58ce to your computer and use it in GitHub Desktop.
Sample Generic Summer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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