英文:
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:"name"`
    } `json:"data"`
}
func Something(c *gin.Context) {
	result := make(chan MyStruct, 1)
	go func() {
		resp, _ := Calculate()  // if return empty slice
        fmt.Println(result)     // output: {[]}
		result <- resp
	}()
	
	c.JSON(http.StatusOK, <-result) // output: {"data": null}
}
Is it possible make the last output <-result to {"data": []}?
答案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:"name"`
}{}
To make this easier, declare a named type for the Data field:
type Data struct {
	Name string `json:"name"`
}
type MyStruct struct {
	Data []Data `json:"data"`
}
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{}}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论