英文:
Why golang struct array cannot be assigned to an interface array
问题
我正在尝试实现以下内容:
package main
import (
"fmt"
)
type MyStruct struct {
Value int
}
func main() {
x := []MyStruct{
MyStruct{
Value: 5,
},
MyStruct{
Value: 6,
},
}
var y []interface{}
y = x // 这会导致编译时错误
_, _ = x, y
}
这会导致编译时错误:
sample.go:21: cannot use x (type []MyStruct) as type []interface {} in assignment
为什么这是不可能的?如果不行,是否有其他方法在 Golang 中保存通用对象数组?
英文:
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?
答案1
得分: 35
interface{}被存储为一个由两个词组成的对,一个词描述底层类型信息,另一个词描述接口中的数据:
https://research.swtch.com/interfaces
在这里,第一个词存储类型信息,第二个词存储b中的数据。
结构体类型的存储方式不同,它们没有这种配对。结构体的字段在内存中依次排列。
https://research.swtch.com/godata
你不能将一个转换为另一个,因为它们在内存中的表示方式不同。
> 需要逐个复制元素到目标切片。
https://golang.org/doc/faq#convert_slice_of_interface
回答你最后一个问题,你可以有[]interface{},它是一个接口切片,其中每个接口都表示如上所述,或者只有interface{},其中接口中持有的底层类型是[]MyStruct。
var y interface{}
y = x
或者
y := make([]interface{}, len(x))
for i, v := range x {
y[i] = v
}
英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。




评论