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

Susan Sarandon
Release: 2024-10-25 14:01:02
Original
963 people have browsed it

## 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.

<code class="go">func Fill[X, Y any](slice []X){
   for i := range slice {
      slice[i] = new(Y) // not work!
   }
}</code>
Copy after login

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:

<code class="go">func Fill[X, Y any](slice []X) {
    for i := range slice {
        slice[i] = any(*new(Y)).(X)
    }
}</code>
Copy after login

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:

<code class="go">func Fill[X any](slice []X, f func() X) {
    for i := range slice {
        slice[i] = f()
    }
}</code>
Copy after login

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{} }.

The above is the detailed content of ## How to Initialize Slices of Interfaces with Concrete Types in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!