Welcome to our comprehensive guide on Go Generics! In this lesson, we'll explore the world of Go's new generic types, which were introduced in Go 1.18. Let's dive in!
Generics are a powerful feature that allows us to write reusable code by defining types that work with multiple data types. This means we can write a single function or type that can work with various data structures like slices, maps, and structs, without having to write multiple versions of the same code.
Go's generic types consist of:
Let's create a simple generic function that swaps the positions of two elements in a slice.
package main
import "fmt"
// swap function takes two generic type parameters T and swaps the positions of two elements.
func swap[T any](slice []T, i, j int) {
temp := slice[i]
slice[i] = slice[j]
slice[j] = temp
}
func main() {
numbers := []int{1, 2, 3, 4, 5}
letters := []string{"a", "b", "c", "d", "e"}
fmt.Println("Numbers before swap:", numbers)
swap(numbers, 1, 2)
fmt.Println("Numbers after swap:", numbers)
fmt.Println("Letters before swap:", letters)
swap(letters, 1, 2)
fmt.Println("Letters after swap:", letters)
}In this example, the swap function is generic, meaning it can work with any data type (specified by the T type parameter). In the main function, we use the swap function with both int and string slices.
What are Go's generic types?
We've just scratched the surface of Go Generics. In future lessons, we'll dive deeper into using generic functions, creating generic structs, and understanding the any type.
Stay tuned and keep coding! 💡