Go:Missing type in composite literal

发布时间 2023-07-21 15:32:10作者: shui00cc

在使用含字符串数组的结构体时,我出现了以下问题

 1 package main
 2 
 3 import "github.com/gin-gonic/gin"
 4 
 5 type MyJson struct {
 6     Functions []string `json:"functions"`
 7     Desc      string `json:"desc"`
 8 }
 9 
10 func main() {
11     r := gin.Default()
12     r.GET("/", func(c *gin.Context) {
13         c.String(200, "值:%v", "首页")
14     })
15     r.GET("/json", func(c *gin.Context) {
16         myJson := &MyJson{
17             Desc:      "三种gin-Json的方法",
18             Functions: {"map[string]interface{}", "gin.H", "struct"},
19         }
20         c.JSON(200, myJson)
21     })
22     r.Run()
23 }

行18报错 : missing type in composite literal

解决:结构体中的数组字段赋值时,声明其类型

Functions: []string{"map[string]interface{}", "gin.H", "struct"}

//==============Json踩坑:

在定义MyJson结构体时,若字段functions、desc使用小写,将导致其无法正常序列化为Json数据

//错误示例
type MyJson struct {
    functions []string
    desc      string
}

注意字段使用大写,可以在定义时使用`json:"functions"`来将其修改为小写显示。