Junior — Middle
Have you had experience using generic types in programming?
sobes.tech AI
Answer from AI
Generic types in Go allow you to write functions and structures that work with different data types while maintaining type safety. With the introduction of generics in Go 1.18, you can declare type parameters and use them in your code.
Here's a simple example of a generic function for swapping the values of two variables:
package main
import "fmt"
type any = interface{}
func Swap[T any](a, b T) (T, T) {
return b, a
}
func main() {
x, y := 1, 2
x, y = Swap(x, y)
fmt.Println(x, y) // 2 1
a, b := "hello", "world"
a, b = Swap(a, b)
fmt.Println(a, b) // world hello
}
Thus, generics enable writing more versatile and reusable code.