Junior — Middle
What types of generic programming are available in the Go language?
sobes.tech AI
Answer from AI
In the Go language, generic programming is implemented through generics, which appeared starting from version 1.18. The main types of generics in Go include:
- Parameterized types (generic types): functions and types can accept type parameters, allowing for writing universal code.
- Interfaces with constraints (type constraints): specify requirements for type parameters, such as supporting certain methods or being from a set of specific types.
Example of a generic function for a slice:
func IndexOf[T comparable](slice []T, val T) int {
for i, v := range slice {
if v == val {
return i
}
}
return -1
}
Here, T is a type parameter constrained by the comparable interface, which allows using the == operator. Such a function is universal for any comparable types.
Thus, Go supports generics through type parameterization and constraints, which increases flexibility and code reuse.