What Are Generics in Go and Why Were They Added

Generics in Go, introduced in version 1.18, enable type-safe, reusable code by allowing functions and types to work with any data type without sacrificing performance.

Generics in Go are a feature added in Go 1.18 that allow functions and types to operate on any type while maintaining type safety, eliminating the need for interface{} and type assertions. They were added to reduce code duplication and improve performance by enabling the compiler to generate specialized code for each type used. You define a generic function using type parameters in square brackets, like [T any], and use them as placeholders for actual types.

func First[T any](slice []T) T {
	return slice[0]
}

func main() {
	fmt.Println(First([]int{1, 2, 3}))
	fmt.Println(First([]string{"a", "b"}))
}