"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > ## How to Initialize Slices of Interfaces with Concrete Types in Go?

## How to Initialize Slices of Interfaces with Concrete Types in Go?

Published on 2024-11-10
Browse:846

## How to Initialize Slices of Interfaces with Concrete Types in Go?

Generic Initialization with Interfaces and Concrete Types in Go

When writing generic functions in Go, it can be beneficial to also accept concrete types. However, this poses a challenge when attempting to initialize slices of interfaces with new instances of those specific types.

Initial Attempts with Multiple Type Parameters

One approach may seem logical: defining two type parameters, one for the slice element type (X) and one for the concrete type (Y) to instantiate. However, this approach fails when trying to assign an instance of Y to an element of type X.

func Fill[X, Y any](slice []X){
   for i := range slice {
      slice[i] = new(Y) // not work!
   }
}

This issue arises because the compiler loses the relationship between the interface X and its implementation Y. Both X and Y are treated as distinct any types.

Using Explicit Casting

To address this, one can employ an explicit casting operation within the function:

func Fill[X, Y any](slice []X) {
    for i := range slice {
        slice[i] = any(*new(Y)).(X)
    }
}

However, this approach triggers a panic if Y does not implement X, which occurs in scenarios such as attempting to assign a *sync.Mutex (pointer type) to sync.Locker.

Utilizing a Constructor Function

A more robust and type-safe solution involves utilizing a constructor function:

func Fill[X any](slice []X, f func() X) {
    for i := range slice {
        slice[i] = f()
    }
}

This function accepts a constructor function that returns a new instance of the specified type. This allows for concise and safe initialization of slices with concrete type instances.

Avoiding Null Values

In cases where the concrete type is intended to be instantiated with a pointer type, it is important to note that new(Y) will result in a nil value. To circumvent this, one can adjust the constructor function to return the correct pointer value, such as func() X { return &sync.Mutex{} }.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3