为什么Golang结构数组无法分配给接口数组

Anu*_*dha 1 go

我正在尝试实现以下目标。

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
}
Run Code Online (Sandbox Code Playgroud)

这给出了编译时错误:

sample.go:21: cannot use x (type []MyStruct) as type []interface {} in assignment
Run Code Online (Sandbox Code Playgroud)

为什么这不可能呢?如果没有,则没有其他方法可以在Golang中保存通用对象数组吗?

Zak*_*Zak 5

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 
Run Code Online (Sandbox Code Playgroud)

要么

y := make([]interface{}, len(x))
for i, v := range x {
    y[i] = v
}
Run Code Online (Sandbox Code Playgroud)