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
int64andfloat64
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
Numberis a type constraint- by doing
[]Number{...}, it’s usingNumberas a real type - but
Numberis not a real type