Home > Backend Development > Golang > How Can I Assign a Go Struct Array to an Interface Array?

How Can I Assign a Go Struct Array to an Interface Array?

DDD
Release: 2024-11-30 19:52:16
Original
507 people have browsed it

How Can I Assign a Go Struct Array to an Interface Array?

Interface Array Assignment Conundrum in Go

In Go, the attempt to assign a struct array directly to an interface array, as shown below, yields a compile-time error:

x := []MyStruct{...}
var y []interface{}
y = x // Error: cannot use x as type []interface {}
Copy after login

This error stems from the fundamental difference in how struct types and interfaces are stored in memory. Interfaces are stored as two-word pairs, comprising type information and data, while struct types are stored as adjacent fields in memory.

Since these representations do not align, direct conversion between the two is not feasible. It is necessary to copy the elements individually to the destination slice.

To resolve this issue, consider one of the following options:

  • Slice of Interfaces: Use a []interface{} slice, where each element is an interface representing the struct type:
var y []interface{}
y = make([]interface{}, len(x))
for i, v := range x {
    y[i] = v
}
Copy after login
  • Interface of Struct Slice: Use an interface{} variable to hold the []MyStruct slice:
var y interface{}
y = x
Copy after login

In the latter scenario, the interface holds an abstract reference to the underlying []MyStruct slice, allowing for polymorphic behavior.

The above is the detailed content of How Can I Assign a Go Struct Array to an Interface Array?. For more information, please follow other related articles on the PHP Chinese website!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template