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
Release: 2024-11-30 19:19:15
Original
242 people have browsed it

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
}
Copy after login
  • 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]}}
Copy after login
  • 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
Copy after login

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!

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