Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define multiple name tags in a struct

Tags:

json

struct

go

People also ask

Can you have multiple tag strings in struct field?

That is, you can have multiple tags in the same field, serving different purposes and libraries. Each package has their own key names, usually the name of the package itself. Some examples of use: Encoding/decoding purposes (like in json and xml packages);

What are struct tags?

A struct tag is additional meta data information inserted into struct fields. The meta data can be acquired through reflection. Struct tags usually provide instructions on how a struct field is encoded to or decoded from a format. Struct tags are used in popular packages including: encoding/json.


It says in the documentation of the reflect package:

By convention, tag strings are a concatenation of optionally space-separated key:"value" pairs. Each key is a non-empty string consisting of non-control characters other than space (U+0020 ' '), quote (U+0022 '"'), and colon (U+003A ':'). Each value is quoted using U+0022 '"' characters and Go string literal syntax.

What you need to do is to use space instead of comma as tag string separator.

type Page struct {
    PageId string                 `bson:"pageId" json:"pageId"`
    Meta   map[string]interface{} `bson:"meta" json:"meta"`
}

Thanks for the accepted answer.

Below is just for the lazy people like me.

INCORRECT

type Page struct {
    PageId string                 `bson:"pageId",json:"pageId"`
    Meta   map[string]interface{} `bson:"meta",json:"pageId"`
}

CORRECT

type Page struct {
    PageId string                 `bson:"pageId" json:"pageId"`
    Meta   map[string]interface{} `bson:"meta" json:"pageId"`
}