Go generics: 6 months in, here's what actually works
Posted by Hanuman Anjaniputra · 2022-06-18
Six months of real-world Go generics. The good: type-safe containers, functional utilities. The bad: no method type parameters. Here's a generic Map/Filter that replaces dozens of hand-written loops. https://github.com/golang/go
// Go generics in practice (Go 1.18+)
func Map[T, U any](slice []T, fn func(T) U) []U {
result := make([]U, len(slice))
for i, v := range slice {
result[i] = fn(v)
}
return result
}
func Filter[T any](slice []T, pred func(T) bool) []T {
var result []T
for _, v := range slice {
if pred(v) {
result = append(result, v)
}
}
return result
}