Golang API响应的通用类型

huangapple go评论80阅读模式
英文:

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)
}

playground

英文:

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)
}

<kbd>playground</kbd>

huangapple
  • 本文由 发表于 2014年7月15日 06:36:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/24747162.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定