Home >Backend Development >Golang >How Can I Assign a Slice of Structs to a Slice of Interfaces in Go?

How Can I Assign a Slice of Structs to a Slice of Interfaces in Go?

Susan Sarandon
Susan SarandonOriginal
2024-11-30 19:19:15245browse

How Can I Assign a Slice of Structs to a Slice of Interfaces in Go?

Assigning Slice of Structs to Interface Slice

When attempting to assign a slice of structs ([]MyStruct) to a slice of interfaces ([]interface{}), you may encounter a compile-time error. This is because structs and interfaces have different memory representations.

Structs have their fields stored adjacent in memory, while interfaces are stored as a two-word pair, one for type information and one for the actual data. This difference prevents direct assignment.

Possible Solutions:

  • Copy Elements Individually: You can manually iterate over the struct slice and copy each element into the interface slice.
y := make([]interface{}, len(x))
for i, v := range x {
    y[i] = v
}
  • Utilize Interface Wrapper: You can create a wrapper type that implements the interface{} interface and holds the underlying struct.
type IMyStruct struct {
    MyStruct
}

func (i IMyStruct) Interface() interface{} {
    return i.MyStruct
}

x := []MyStruct{{5}, {6}}
y := []interface{}{IMyStruct{x[0]}, IMyStruct{x[1]}}
  • Use Empty Interface: You can assign the slice of structs to an empty interface, which can hold values of any type.
var y interface{}
y = x // No type conversion required

The above is the detailed content of How Can I Assign a Slice of Structs to a Slice of Interfaces in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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