deeper understanding of generics

tags: learning go programming

content

up

  • i wrote this code, goal is to sum up numbers in an array consisting of int64 and float64
type Number interface {
	int64 | float64
}
func AddNums[T Number](nums []T) float64 {
	sum := float64(0)
	for _, v := range nums {
		sum += v
	}
	return sum
}
nums := []Number{int64(1), float64(2.2)}
sum := AddNumbes(nums)
  • this doesn’t work because
    • Number is a type constraint
    • by doing []Number{...}, it’s using Number as a real type
    • but Number is not a real type

down

reference