英文:
Catchall type for Golang API response
问题
我正在尝试定义一个可以容纳任意类型数组的结构体,如下所示:
type APIResponse struct {
length int
data []interface{}
}
我希望data
属性能够容纳任意类型/结构体的数组,这样我就可以拥有一个单一的响应类型,最终将其序列化为JSON。所以我想要编写的代码类似于以下内容:
someStruct := getSomeStructArray()
res := &APIResponse{
length: len(someStruct),
data: someStruct,
}
enc, err := json.Marshal(res)
在Go语言中是否可能实现这个目标?我一直得到cannot use cs (type SomeType) as type []interface {} in assignment
的错误。或者我必须为每种数据类型创建不同的响应类型?或者我完全错误地处理了这个问题,不符合Go语言的风格。非常感谢任何帮助!
英文:
I am trying to define a struct that can hold an array of any type like so:
type APIResonse struct {
length int
data []interface{}
}
I want the data
property to be capable of holding an array of any type/struct so I can have a single response type, that will eventually be serialized to json. So what I want to be able to write is something like the following:
someStruct := getSomeStructArray()
res := &APIResponse{
length: len(someStruct),
data: someStruct,
}
enc, err := json.Marshal(res)
Is this possible in Go? I keep getting cannot use cs (type SomeType) as type []interface {} in assignment
. Or do I have to create a different response type for every variation of data? Or maybe I am going about this wrong entirely / not Go-like. Any help would be much appreciated!
答案1
得分: 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)
}
英文:
There are a couple of problems with that code.
You need to use interface{}
, not []interface{}
, also []
is called a slice, an array is a fixed number of elements like [10]string
.
And your APIResponse
fields aren't exported, so json.Marshal
will not print out anything.
func main() {
d := []dummy{{100}, {200}}
res := &APIResponse{
Length: len(d),
Data: d,
}
enc, err := json.Marshal(res)
fmt.Println(string(enc), err)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论