Junior — Middle
Milline on üldtüüpide (Generics) roll Go keeles ja millised on nende eelised?
sobes.tech AI
Vastus AI-lt
Generics in Go allow you to write functions, structures, and interfaces that work with different data types while maintaining type safety. This increases code reusability and reduces duplication.
Advantages of Generics in Go:
- Enable the creation of universal algorithms and data structures.
- Maintain strict type checking, preventing errors during compilation.
- Improve code readability and maintainability.
Example of using Generics in Go:
package main
import "fmt"
func PrintSlice[T any](s []T) {
for _, v := range s {
fmt.Println(v)
}
}
func main() {
ints := []int{1, 2, 3}
strings := []string{"a", "b", "c"}
PrintSlice(ints)
PrintSlice(strings)
}