2017-06-02 108 views
0

我想下面實現的東西。爲什麼golang結構陣列不能分配給接口陣列

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 
} 

這給出了一個編譯時錯誤:

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

爲什麼這是不可能的。如果不是有沒有任何其他方式在Golang持有通用對象數組?

+2

由於*一般類型*數組不等於*一個struct *陣列。只需使用'var y interface {}'而不是數組。類型'interface {}'可以用來存儲** Golang中的任何類型的變量**。 – putu

+0

@putu由於改變接口{}解決了這個問題 – Anuruddha

+1

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

回答

2

interface{}被存儲爲描述的基礎類型的信息和一個字描述該接口內的數據的兩字對,一個字:

enter image description here

https://research.swtch.com/interfaces

在這裏,我們看到的第一個字存儲的類型信息和所述第二內b的數據。

結構類型存儲方式不一樣,他們沒有這樣的配對。它們的結構域在內存中彼此相鄰。

enter image description here

https://research.swtch.com/godata

不能轉換一個到另一個,因爲他們沒有在內存中相同的表示。

It is necessary to copy the elements individually to the destination slice.

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 
}