简体   繁体   English

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

[英]“missing type in composite literal” when passing value to 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: 我希望它能成功,但是VSCode却给我这个错误:

missing type in composite literal

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"} },
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM