Initializing a variable in a struct while declaring a custom json name returns syntax error: unexpected literal

Initializing a variable in a struct while declaring a custom json name returns syntax error: unexpected literal

我想在结构中声明一个变量,对其进行初始化,同时为其声明一个自定义 json 名称。然而编译器总是returns一个语法错误。

可以在实例的结构声明期间初始化值

type Person struct {
        CategoryId     string "Generic"    
        Name           string     `json:"name"`
        Surname        string     `json:"surname"`
    }

可以声明自定义 json 名称。

type Person struct {
        CategoryId     string  `json:"category_id"`    
        Name           string     `json:"name"`
        Surname        string     `json:"surname"`
    }

但是下面的代码returns出错了

type Person struct {
    CategoryId     string "Generic"  `json:"category_id"`    
    Name           string     `json:"name"`
    Surname        string     `json:"surname"`
}

返回的错误如下

syntax error: unexpected literal json:"category_id", expecting semicolon or newline or }

正确的语法是什么? 我尝试了如下几种组合:

type Person struct {
    CategoryId     string "Generic"  `json:"category_id"`;  
    Name           string     `json:"name"`
    Surname        string     `json:"surname"`
}

type Person struct {
    CategoryId     string "Generic";  `json:"category_id"`
    Name           string     `json:"name"`
    Surname        string     `json:"surname"`
}

但是上面的none是正确的语法。我也很感激 link 到我可以阅读更多关于这个语法的地方。

该字段声明:

CategoryId     string "Generic" 

不是初始化(不能在类型声明中为Go中的字段指定默认值)。末尾的字符串文字 "Generic" 是该字段的标记值。与此相同:

CategoryId     string `Generic` 

使用原始的还是解释的都没有关系string literal,您只能在那里提供一个文字,它将成为字段的标签。

如果您想为单个字段提供多个标记值,按照惯例,您必须在单个文字中用 space 分隔它们,例如:

CategoryId     string `Generic json:"category_id"`

语法详见Spec: Struct types:

A field declaration may be followed by an optional string literal tag, which becomes an attribute for all the fields in the corresponding field declaration. An empty tag string is equivalent to an absent tag. The tags are made visible through a reflection interface and take part in type identity for structs but are otherwise ignored.

有关概述、更多详细信息和惯例,我强烈建议阅读此相关问题:What are the use(s) for tags in Go?