Sobes.tech
Junior — Middle

Explain the concept of generic programming using Generics in the Go language.

sobes.tech AI

Answer from AI

Generic programming in Go allows writing functions, types, and structures that work with different data types while maintaining type safety. Instead of using interface{} and type assertions, Generics enable parameterizing types.

Example of a function with Generics:

func PrintSlice[T any](s []T) {
    for _, v := range s {
        fmt.Println(v)
    }
}

Here, T is a type parameter, and 'any' means any type. Such a function can accept slices of any types, for example, []int or []string.

Generics help write more versatile and safe code, reducing duplication.