2014-07-14 31 views
-1

我試圖限定,可容納任何類型的數組,像這樣的結構體:全部接收類型Golang API響應

type APIResonse struct { 
    length int 
    data []interface{} 
} 

我希望data屬性爲能夠保持任何類型的陣列/結構,所以我可以有一個單一的響應類型,最終將序列化爲json。所以我想寫的東西是這樣的:

someStruct := getSomeStructArray() 
res := &APIResponse{ 
    length: len(someStruct), 
    data: someStruct, 
} 
enc, err := json.Marshal(res) 

這是可能的去吧?我一直得到cannot use cs (type SomeType) as type []interface {} in assignment。還是必須爲每個數據變體創建不同的響應類型?或者,我可能完全/不是Go-like。任何幫助將非常感激!

+0

使用'接口{}',而不是它的數組,你可以把任何你想在那裏。 –

+0

@Not_a_Golfer我仍然得到'不能使用'的錯誤。 – grep

回答

2

該代碼存在一些問題。

需要使用interface{},不[]interface{},也[]被稱爲切片,陣列是像[10]string元素的固定數量。

而且您的APIResponse字段未導出,因此json.Marshal不會打印出任何內容。

func main() { 
    d := []dummy{{100}, {200}} 
    res := &APIResponse{ 
     Length: len(d), 
     Data: d, 
    } 
    enc, err := json.Marshal(res) 
    fmt.Println(string(enc), err) 
} 

playground