Golang API响应的通用类型

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

Catchall type for Golang API response

问题

我正在尝试定义一个可以容纳任意类型数组的结构体,如下所示:

  1. type APIResponse struct {
  2. length int
  3. data []interface{}
  4. }

我希望data属性能够容纳任意类型/结构体的数组,这样我就可以拥有一个单一的响应类型,最终将其序列化为JSON。所以我想要编写的代码类似于以下内容:

  1. someStruct := getSomeStructArray()
  2. res := &APIResponse{
  3. length: len(someStruct),
  4. data: someStruct,
  5. }
  6. 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:

  1. type APIResonse struct {
  2. length int
  3. data []interface{}
  4. }

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:

  1. someStruct := getSomeStructArray()
  2. res := &APIResponse{
  3. length: len(someStruct),
  4. data: someStruct,
  5. }
  6. 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不会输出任何内容。

  1. func main() {
  2. d := []dummy{{100}, {200}}
  3. res := &APIResponse{
  4. Length: len(d),
  5. Data: d,
  6. }
  7. enc, err := json.Marshal(res)
  8. fmt.Println(string(enc), err)
  9. }

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.

  1. func main() {
  2. d := []dummy{{100}, {200}}
  3. res := &APIResponse{
  4. Length: len(d),
  5. Data: d,
  6. }
  7. enc, err := json.Marshal(res)
  8. fmt.Println(string(enc), err)
  9. }

<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:

确定