Golang Generics Interface: Understanding with Abundant Practical Examples

Hello, today we’ll focus on Golang’s generics and interfaces, explaining them through a variety of concrete examples. Generics and interfaces are powerful features in Golang, and understanding these concepts can help you write more effective code. Let’s get started.

What Are Generics?

Generics are a mechanism for performing common algorithms or data structure operations on different data types. This enhances code reusability and maintains type safety.

Here’s an example of a simple slice reversal function using generics:

package main

import "fmt"

func Reverse[T any](s []T) []T {
    for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
        s[i], s[j] = s[j], s[i]
    }
    return s
}

func main() {
    ints := []int{1, 2, 3, 4, 5}
    reversedInts := Reverse(ints)
    fmt.Println(reversedInts)

    strings := []string{"apple", "banana", "cherry"}
    reversedStrings := Reverse(strings)
    fmt.Println(reversedStrings)
}

In this example, we’re implementing the Reverse function generically. This code can be applied not only to slices of type int but also to slices of type string.

Combining Interfaces and Generics

Generics can be used to perform common operations on different types of data. When combined with interfaces, even more flexibility can be achieved. Here’s an example:

package main

import (
    "fmt"
)

type Shape interface {
    Area() float64
}

type Rectangle struct {
    Width  float64
    Height float64
}

func (r Rectangle) Area() float64 {
    return r.Width * r.Height
}

type Circle struct {
    Radius float64
}

func (c Circle) Area() float64 {
    return 3.14 * c.Radius * c.Radius
}

func CalculateArea[T Shape](shape T) float64 {
    return shape.Area()
}

func main() {
    rectangle := Rectangle{Width: 5, Height: 10}
    circle := Circle{Radius: 7}

    fmt.Printf("Rectangle Area: %.2f\n", CalculateArea(rectangle))
    fmt.Printf("Circle Area: %.2f\n", CalculateArea(circle))
}

In this code, we define a Shape interface, and the Rectangle and Circle structs implement it. Using generics, we define the CalculateArea function, which can perform a generic area calculation on different shapes.

Conclusion

Generics and interfaces are powerful tools for writing efficient and flexible code in Golang. This article explained these concepts through concrete code examples. By combining generics with interfaces, you can enhance code reusability and type safety. We encourage you to apply these concepts to your own projects.

タイトルとURLをコピーしました