Senior
What are generics in Go? How do you understand?
sobes.tech AI
Answer from AI
Generics in Go are a mechanism that allows writing functions, types, and structures that work with different data types while maintaining type safety.
Before generics appeared in Go, it was necessary to use interfaces or write repetitive code for different types. With generics, you can define parameterized types with constraints that specify which types are permissible.
Example of a generic function:
func Max[T comparable](a, b T) T {
if a > b {
return a
}
return b
}
Here, T is a type parameter constrained by the comparable interface (types that support comparison operations). The Max function returns the larger of two values of type T.
Thus, generics enable writing more universal and reusable code, maintaining strict typing and avoiding the use of interface{} and type assertions.