skip to content
Alvin Lucillo

Go generics

/ 1 min read

💻 Tech

You can do generics in Go starting from Go 1.18. Generics makes it possible to write data structures and functions that can work with any type. Without using generics, the code below would have to be written twice doing the same thing.

// Generic type
type Number interface {
	int | float64
}

func main() {
	fmt.Println(sum([]int{1, 2, 3, 4, 5})) // 15
	fmt.Println(sum([]float64{1, 2, 3, 4, 5})) // 15
}

// Generic function that takes in either array of int or float64
// Without the Number interface, you can the function as sum[T int|float64](nums []T) T
func sum[T Number](nums []T) T {
	var sum T
	for _, n := range nums {
		sum += n
	}
	return sum
}