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

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

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

问题

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

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

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

英文:

if resp is struct with slice member like following:

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

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

答案1

得分: 1

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

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

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

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

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

type Data struct {
	Name string `json:"name"`
}

type MyStruct struct {
	Data []Data `json:"data"`
}

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

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:

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

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

type Data struct {
	Name string `json:&quot;name&quot;`
}

type MyStruct struct {
	Data []Data `json:&quot;data&quot;`
}

Set the field to the empty slice using:

resp.Data = []Data{}

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

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:

确定