当使用gin.Context.JSON返回时,如果没有数据,会返回一个空的切片。

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

Go - empty slice when return by gin.Context.JSON

问题

如果resp是一个包含切片成员的结构体,如下所示:

  1. type MyStruct struct {
  2. Data []struct {
  3. Name string `json:"name"`
  4. } `json:"data"`
  5. }
  1. func Something(c *gin.Context) {
  2. result := make(chan MyStruct, 1)
  3. go func() {
  4. resp, _ := Calculate() // 如果返回空切片
  5. fmt.Println(result) // 输出: {[]}
  6. result <- resp
  7. }()
  8. c.JSON(http.StatusOK, <-result) // 输出: {"data": null}
  9. }

是否可能将最后的输出<-result改为{"data": []}

英文:

if resp is struct with slice member like following:

  1. type MyStruct struct {
  2. Data []struct {
  3. Name string `json:&quot;name&quot;`
  4. } `json:&quot;data&quot;`
  5. }
  1. func Something(c *gin.Context) {
  2. result := make(chan MyStruct, 1)
  3. go func() {
  4. resp, _ := Calculate() // if return empty slice
  5. fmt.Println(result) // output: {[]}
  6. result &lt;- resp
  7. }()
  8. c.JSON(http.StatusOK, &lt;-result) // output: {&quot;data&quot;: null}
  9. }

Is it possible make the last output &lt;-result to {&quot;data&quot;: []}?

答案1

得分: 1

fmt包将nil切片打印为与空切片相同的形式:[]

json/encoding包区分nil切片和空切片。nil切片被编码为nil,而空切片被编码为[]

要获得预期的输出,将Data字段设置为空切片:

  1. resp.Data = []struct {
  2. Name string `json:"name"`
  3. }{}

为Data字段声明一个命名类型,以便更容易操作:

  1. type Data struct {
  2. Name string `json:"name"`
  3. }
  4. type MyStruct struct {
  5. Data []Data `json:"data"`
  6. }

使用短变量声明和包含空切片的复合字面量将赋值与变量声明结合起来:

  1. resp := MyStruct{Data: []Data{}}
英文:

The fmt package prints nil slices the same as empty slices: [].

The json/encoding package makes a distinction between nil slices and empty slices. A nil slice is encode as nil and an empty slice is encoded as [].

To get the expected output, set the Data field to an empty slice:

  1. resp.Data = []struct {
  2. Name string `json:&quot;name&quot;`
  3. }{}

To make this easier, declare a named type for the Data field:

  1. type Data struct {
  2. Name string `json:&quot;name&quot;`
  3. }
  4. type MyStruct struct {
  5. Data []Data `json:&quot;data&quot;`
  6. }

Set the field to the empty slice using:

  1. resp.Data = []Data{}

Combine this assignment with the variable declaration by using a short variable declaration and a composite literal containing the empty slice:

  1. resp := MyStruct{Data: []Data{}}

huangapple
  • 本文由 发表于 2022年8月23日 23:58:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/73461793.html
匿名

发表评论

匿名网友

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

确定