Welcome to our deep dive into Go's Generic Data Structures! In this lesson, we'll explore how to create flexible and reusable data structures in Go using Generics. Let's embark on this exciting journey together!
Generics in Go are a way to define reusable code that works with multiple data types. They help us write flexible, modular, and efficient code.
Go's Generic functions and types use T as the type parameter. In the following examples, we'll see how to define and use generic functions and types.
Let's create a simple generic function that swaps two elements.
package main
import "fmt"
func swap[T comparable](arr []T, i, j int) {
temp := arr[i]
arr[i] = arr[j]
arr[j] = temp
}
func main() {
data := []int{1, 2, 3, 4, 5}
fmt.Println("Before swap:", data)
swap(data, 1, 3)
fmt.Println("After swap:", data)
}In this example, we define a generic swap function that accepts an array and two indices. The function uses the type parameter T to work with any comparable type.
Now, let's create a generic Stack type.
package main
import "fmt"
type Stack[T any] struct {
items []T
}
func (s *Stack[T]) Push(val T) {
s.items = append(s.items, val)
}
func (s *Stack[T]) Pop() T {
if len(s.items) == 0 {
panic("Stack is empty")
}
last := s.items[len(s.items)-1]
s.items = s.items[:len(s.items)-1]
return last
}
func main() {
intStack := &Stack[int]{}
intStack.Push(1)
intStack.Push(2)
intStack.Push(3)
fmt.Println("Int Stack:", intStack.items)
fmt.Println("Popped:", intStack.Pop())
fmt.Println("Int Stack after Pop:", intStack.items)
}In this example, we define a generic Stack type that uses the type parameter T to store any data type. The Push and Pop methods work with the generic T type.
Generic data structures can be used in various real-world projects, such as building efficient data processing pipelines, implementing data-driven algorithms, and creating flexible APIs.
What is the main advantage of using Generics in Go?
With this lesson, you now have a solid understanding of Go's Generic Data Structures. You're well-equipped to create flexible and reusable code in your projects. Happy coding! 🚀