Welcome to the exciting world of Go Generic Types! In this lesson, we'll explore how to create and use generic types in Go, a powerful programming language known for its simplicity and efficiency. Let's get started! 🎯
In Go, we don't have true generics like other languages such as C# or Java. Instead, we use interfaces and type parameters to achieve similar functionality. Let's dive into it!
Interfaces are a fundamental concept in Go that define a set of methods a type must implement. They help us write flexible, reusable code.
// Example of an interface
type Shape interface {
Area() float64
}Here, we've defined an interface called Shape that requires any type implementing it to have an Area() method.
Type parameters allow us to define a type that can be instantiated with different types. They help us create more flexible and reusable code.
// Example of a type with a type parameter
type Container[T any] struct {
Items []T
}Here, we've defined a struct called Container that takes a type parameter T. This means we can create a Container for any type.
Now that we've learned about interfaces and type parameters, let's see how we can use them together to create generic types.
We can create a simple generic list by using our Container struct and the Shape interface.
// Implementing the Shape interface for two shapes
type Circle struct {
Radius float64
}
type Rectangle struct {
Width, Height float64
}
// Circle implements the Shape interface
func (c Circle) Area() float64 {
return 3.14 * c.Radius * c.Radius
}
// Rectangle implements the Shape interface
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
// Using the Container struct with the Shape interface
func main() {
circle := Circle{Radius: 5}
rectangle := Rectangle{Width: 4, Height: 6}
container := Container[Shape]{Items: []Shape{circle, rectangle}}
for _, item := range container.Items {
fmt.Println("Area:", item.Area())
}
}In this example, we've created a Circle and Rectangle that implement the Shape interface. We then use the Container struct to create a list of shapes. In the main function, we iterate over the list and print the area of each shape.
We can also create generic functions to work with multiple types.
// A generic function for swapping two values
func swap[T any](x, y *T) {
tmp := *x
*x = *y
*y = tmp
}
// Example usage
var x int = 10
var y string = "Hello"
swap(&x, &y)
fmt.Println("x:", x) // Output: 10
fmt.Println("y:", y) // Output: HelloIn this example, we've created a swap function that takes two pointers of any type T. We then use this function to swap the values of x and y, which are of different types.
What is the purpose of the `Container` struct in Go?
In this lesson, we've explored Go's approach to generic types using interfaces and type parameters. We've seen how to create generic lists and generic functions, making our code more flexible and reusable. As you continue learning Go, remember to keep practicing and exploring new concepts! 🚀
Happy coding! 💻