Skip to content

Commit

Permalink
add generics example (compatible with go1.18 and above)
Browse files Browse the repository at this point in the history
  • Loading branch information
SimonWaldherr committed Dec 29, 2021
1 parent c80b8f4 commit e8e0729
Showing 1 changed file with 58 additions and 0 deletions.
58 changes: 58 additions & 0 deletions expert/generics.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package main

import (
"fmt"
)

type Number interface {
int64 | float64
}

func SumInts(m ...int64) int64 {
var s int64
for _, v := range m {
s += v
}
return s
}

func SumFloats(m ...float64) float64 {
var s float64
for _, v := range m {
s += v
}
return s
}

func SumIntsOrFloats[V int64 | float64](m ...V) V {
var s V
for _, v := range m {
s += v
}
return s
}

func SumNumbers[V Number](m ...V) V {
var s V
for _, v := range m {
s += v
}
return s
}

func main() {
ints := []int64{31, 37, 41, 43, 47, 53, 59}
floats := []float64{31.17, 37.2, 41.9, 43.002, 47, 53, 59}

fmt.Printf("Non-Generic Sums: %v and %v\n",
SumInts(ints...),
SumFloats(floats...))

fmt.Printf("Generic Sums: %v and %v\n",
SumIntsOrFloats(ints...),
SumIntsOrFloats(floats...))

fmt.Printf("Generic Sums: %v and %v\n",
SumNumbers(ints...),
SumNumbers(floats...))
}

0 comments on commit e8e0729

Please sign in to comment.