将值传递给struct时“复合文字中缺少类型”

问题描述:

I have defined my struct like this this below:

type S_LoginSuccessed struct {
    Code int `json:"code"`
    Data struct {
        User struct {
            Sex   string `json:"sex"`
            IsVip bool   `json:"is_vip"`
            Name  string `json:"name"`
        } `json:"user"`
    } `json:"data"`
    Timestamp int64  `json:"timestamp"`
    Message   string `json:"message"`
}

And I use this to call it:

success_message := S_LoginSuccessed{123, {{"male", true, "123"}}, time.Now().Unix(), "123"}

I expect it to be success, How ever the VSCode give me this error:

missing type in composite literal

我在下面定义了这样的结构: p>

  类型S_Login成功的结构{
代码int`json:“ code”`
数据结构{
用户结构{
性别字符串`json:“ sex”`
 IsVip bool`json:“ is_vip”`
名称 字符串`json:“ name”`
}`json:“ user”`
}`json:“ data”`
 Timestamp int64`json:“ timestamp”`
消息字符串`json:“ message”`  
} 
  code>  pre> 
 
 

我用它来称呼它: p>

  success_message:= S_LoginSuccessed {123,{  {“ male”,true,“ 123”}},time.Now()。Unix(),“ 123”} 
  code>  pre> 
 
 

我希望它会成功 ,VSCode为何会给我这个错误: p>

 复合文字中的缺少类型
  code>  pre> 
  div>

If you declare the struct in the way you did (nesting structs without creating new types), using them in literals is convoluted as you need to repeat the struct definition.

You'll be forced to use it like this:

success_message := S_LoginSuccessed{
    Code: 123,
    Timestamp: time.Now().Unix(),
    Message: "123",
    Data: struct {
        User struct {
            Sex   string `json:"sex"`;
            IsVip bool   `json:"is_vip"`;
            Name  string `json:"name"`
        }
    }{User: struct {
        Sex   string
        IsVip bool
        Name  string
    }{Sex: "male", IsVip: true, Name: "123"}},
}

Might be more modular to declare the types like this:

type User struct {
    Sex   string `json:"sex"`
    IsVip bool   `json:"is_vip"`
    Name  string `json:"name"`
}

type Data struct{
    User User `json:"user"`
}

type S_LoginSuccessed struct {
    Code int `json:"code"`
    Data Data `json:"data"`
    Timestamp int64  `json:"timestamp"`
    Message   string `json:"message"`
}

Then use it like this:

success_message := S_LoginSuccessed{
    Code: 123,
    Timestamp: time.Now().Unix(),
    Message: "123",
    Data: Data{ User: User{"male", true, "123"} },
}