Go generics help with a simple problem below, which is repetitive code created to handle multiple data types.
func main() {
fmt.Println(GetFirstValueInt([]int{1, 2, 3}))
fmt.Println(GetFirstValueString([]string{"one"}))
}
func GetFirstValueInt(values []int) int {
return values[0]
}
func GetFirstValueString(values []string) string {
return values[0]
}
Without generics, you could say we can just use an interface type, but that loses compile-time knowledge of the type and requires you to make type assertion.
func main() {
fmt.Println(GetFirstValue([]int{1, 2, 3}))
fmt.Println(GetFirstValue([]string{"one"}))
}
func GetFirstValue(values any) any {
switch v := values.(type) {
case []int:
return v[0]
case []string:
return v[0]
default:
return nil
}
}
This is where generics comes to help. When you call the function, it doesn’t return an interface but the actual type of the value.
func GetFirstValue[T any](values []T) T {
return values[0]
}