Home >Backend Development >Golang >## How to Initialize Slices of Interfaces with 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.
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>
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.
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>
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.
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>
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.
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!