doufan1899 2017-06-02 02:30 采纳率: 100%
浏览 249
已采纳

为什么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条回答 默认 最新

  • douan7529 2017-06-02 08:14
    关注

    interface{} is stored as a two word pair, one word describing the underlying type information and one word describing the data within that interface:

    enter image description here

    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.

    enter image description here

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。
  • ¥20 CST怎么把天线放在座椅环境中并仿真
  • ¥15 任务A:大数据平台搭建(容器环境)怎么做呢?