Home > Article > Backend Development > Can Go\'s `interface{}` Arrays Directly Hold Struct Arrays?
In Go, assigning a struct array directly to an interface array raises a compile-time error. To understand why, let's delve into the underlying mechanisms.
interface{} represents a generic type that can store any value. However, it's internally represented as a two-word pair:
In contrast to interfaces, structs store their fields contiguously in memory, without a separate type word.
Since structs and interfaces have different memory representations, they cannot be assigned directly. The type system ensures this to maintain type safety.
To achieve the desired behavior, consider these options:
Using a Slice of Interfaces
You can create a slice of interfaces and assign the struct elements individually:
y := make([]interface{}, len(x)) for i, v := range x { y[i] = v }
Storing an Interface to the Slice
Alternatively, store an interface to the struct slice:
var y interface{} y = x
The above is the detailed content of Can Go\'s `interface{}` Arrays Directly Hold Struct Arrays?. For more information, please follow other related articles on the PHP Chinese website!