Sobes.tech
Middle+

Do you use generics in Go?

sobes.tech AI

Answer from AI

Yes, generics in Go are actively used, especially after their introduction in Go 1.18. They allow writing generic code that works with different types without duplication.

Here's a simple example of a generic function for slices:

func ReverseSlice[T any](s []T) []T {
    result := make([]T, len(s))
    for i, v := range s {
        result[len(s)-1-i] = v
    }
    return result
}

Usage:

ints := []int{1, 2, 3}
revInts := ReverseSlice(ints)

strings := []string{"a", "b", "c"}
revStrings := ReverseSlice(strings)

Generics help create more versatile libraries and simplify code maintenance, reducing duplication and increasing type safety.