2014-07-14 32 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