String literals in GO structure definition

2019-05-24 23:24发布

问题:

In this structure definition:

type API struct {
    Message string "json:message"
}

what is the meaning of the string "json:message" and how to access it if it is accessible. Thank you in advance.

回答1:

These are struct tags. This struct tag is used by package encoding/json to Marshal objects to JSON and Unmarshal JSON string to objects

while marshaling (encoding ) a struct to JSON string it will look for this struct tag to assign JSON key name, if not present it may use the struct field name itself

btw the syntax is wrong it has to be

type API struct {
    Message string `json:"message"`
}

Here is a sample program for reference https://play.golang.org/p/FsMGNuDB8P



标签: go struct