go - What is the use of tag in golang struct? -


i don't understand significance of struct tags. have been looking them, , noticed can used reflect package. don't know practical uses of them.

type tagtype struct { // tags     field1 bool   “an important answer”     field2 string “the name of thing”     field3 int    “how there are” } 

the use of tags depends on how struct used.

a typical use add specifications or constraints persistence or serialisation.

for example, when using json parser/encoder, tags used specify how struct read json or written in json, when default encoding scheme (i.e. name of field) isn't used.

here few examples json package documentation :

// field ignored package. field int `json:"-"`  // field appears in json key "myname". field int `json:"myname"`  // field appears in json key "myname" , // field omitted object if value empty, // defined above. field int `json:"myname,omitempty"`  // field appears in json key "field" (the default), // field skipped if empty. // note leading comma. field int `json:",omitempty"` 

Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -