Practical Examples of Using Golang Generic Structs

Hello, in this article, we will focus on Golang generic structs and explore their practical use cases. Generic structs are a convenient tool for handling various data types flexibly. Below, we’ll provide several concrete code examples.

Basics of Generic Structs

To understand Golang generic structs, let’s start with a basic example.

package main

import "fmt"

type GenericStruct[T any] struct {
    Value T
}

func main() {
    intStruct := GenericStruct[int]{Value: 42}
    strStruct := GenericStruct[string]{Value: "Hello, generics!"}

    fmt.Println(intStruct.Value)
    fmt.Println(strStruct.Value)
}

In this code, we define a generic struct named GenericStruct and create struct instances with different data types (int and string).

Applying Generic Structs to Slices

Next, let’s look at an example of applying generic structs to slices.

package main

import "fmt"

type GenericStruct[T any] struct {
    Value T
}

func main() {
    intSlice := []GenericStruct[int]{
        {Value: 1},
        {Value: 2},
        {Value: 3},
    }

    strSlice := []GenericStruct[string]{
        {Value: "apple"},
        {Value: "banana"},
        {Value: "cherry"},
    }

    fmt.Println(intSlice)
    fmt.Println(strSlice)
}

In this code, we store generic structs with different data types in slices, allowing us to easily create slices containing elements of different types.

Methods for Generic Structs

You can also add methods to generic structs. Here’s an example.

package main

import "fmt"

type GenericStruct[T any] struct {
    Value T
}

func (gs *GenericStruct[T]) PrintValue() {
    fmt.Println(gs.Value)
}

func main() {
    intStruct := GenericStruct[int]{Value: 42}
    strStruct := GenericStruct[string]{Value: "Hello, generics!"}

    intStruct.PrintValue()
    strStruct.PrintValue()
}

In this code, we add the PrintValue method to a generic struct and print the value in a generic way.

Benefits of Generic Structs

Using generic structs allows you to reuse common code for different data types, reducing code redundancy. At the same time, you can maintain type safety while enhancing code flexibility.

By referring to these code examples, you can explore how to use Golang generic structs effectively. Generic structs are a powerful tool that can be used effectively in many scenarios.

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