I'm trying to achieve something as below.
package main
import (
"fmt"
)
type MyStruct struct {
Value int
}
func main() {
x := []MyStruct{
MyStruct{
Value : 5,
},
MyStruct{
Value : 6,
},
}
var y []interface{}
y = x // This throws a compile time error
_,_ = x,y
}
This gives a compile time error:
sample.go:21: cannot use x (type []MyStruct) as type []interface {} in assignment
Why is this not possible?.If not is there any other way to hold generic object arrays in Golang?
interface{}
is stored as a two word pair, one word describing the underlying type information and one word describing the data within that interface:
https://research.swtch.com/interfaces
Here we see the first word stores the type information and the second the data within b
.
Struct types are stored differently, they do not have this pairing. Their fields of a struct are laid out next to one another in memory.
https://research.swtch.com/godata
You cannot convert one to the other because they do not have the same representation in memory.
It is necessary to copy the elements individually to the destination slice.
https://golang.org/doc/faq#convert_slice_of_interface
To answer your last question, you could have []interface
which is a slice of interfaces, where each interface is represented as above, or just interface{}
where the underlying type held in that interface is []MyStruct
var y interface{}
y = x
or
y := make([]interface{}, len(x))
for i, v := range x {
y[i] = v
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With