snippetgoModeratepending
Go generics -- type parameters for reusable functions
Viewed 0 times
Go 1.18+
genericstype parameterconstraintcomparableanyGo 1.18
go
Problem
Before generics, Go required interface{} (any) for generic containers and algorithms, losing type safety and requiring type assertions.
Solution
Go 1.18+ generics with type parameters and constraints. Use for containers, algorithms, and utility functions.
Code Snippets
Generic functions with constraints
// Generic function
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
}
// Constraint
type Number interface {
int | int64 | float64
}
func Sum[T Number](nums []T) T {
var total T
for _, n := range nums {
total += n
}
return total
}
// Usage
names := Map(users, func(u User) string { return u.Name })
adults := Filter(users, func(u User) bool { return u.Age >= 18 })
total := Sum([]int{1, 2, 3, 4, 5})Revisions (0)
No revisions yet.