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

为什么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?

图片转代码服务由CSDN问答提供 功能建议

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

 包main 
 
import(
“ fmt” 
)
 
type MyStruct struct {
 Value int 
} 
 
func main()  {
x:= [] MyStruct {
 MyStruct {
值:5,
},
 MyStruct {
值:6,
},
} 
 var y []界面{} \  ny = x //这会引发编译时间错误
 
 _,_ = x,y 
} 
   
 
 

这会产生编译时间错误:< /p>

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

为什么不行?如果没有,则没有其他方法可以在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
    }
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题