为什么Golang结构数组无法分配给接口数组 [英] Why golang struct array cannot be assigned to an interface array

查看:126
本文介绍了为什么Golang结构数组无法分配给接口数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 程序包主要进口 ("fmt")输入MyStruct struct {值int}func main(){x:= [] MyStruct {MyStruct {价值:5},MyStruct {价值:6},}var y [] interface {}y = x//这会引发编译时错误_,_ = x,y} 

这会导致编译时错误:

  sample.go:21:不能在分配中使用x(类型[] MyStruct)作为类型[] interface {} 

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

解决方案

接口{} 存储为两个单词对,一个单词描述基础类型信息,另一个单词描述其中的数据.界面:

https://research.swtch.com/godata

您不能将一个转换为另一个,因为它们在内存中没有相同的表示形式.

有必要将元素分别复制到目标位置切片.

https://golang.org/doc/faq#convert_slice_of_interface

要回答您的最后一个问题,您可以使用 [] interface (这是接口的一部分),其中每个接口都如上所示,或者只是 interface {} 该接口中保留的基础类型为 [] MyStruct

 各种接口{}y = x 

  y:= make([] interface {},len(x))对于i,v:=范围x {y [i] = v} 

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
}

这篇关于为什么Golang结构数组无法分配给接口数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆