runsisi's

technical notes

go struct tags

2019-03-28 runsisi#golang

tag

  1. A struct tag is a string literal (because it has the string type)
  2. Key is an unquoted string literal
  3. Value is a quoted string literal
  4. Key and value are separated by a colon (:). A key together with a value, separated by the colon is called a “key value pair“
  5. A struct tag can contain multiple key value pairs (optional). The key-value pairs are separated by a space.
  6. Not part of the definition is the options setting. Packages like encoding/json read the value as a comma-separated list. Anything after the first comma is part of the options, i.e: “foo,omitempty,string“. Here the value has a name called “foo” and options [“omitempty”, “string”]
  7. Because the struct tag is a string literal, it needs to be quoted either with a double quote or backtick. Because the value has to be quoted as well we always use backticks.

参考资料

The ultimate guide to writing a Go tool

https://arslan.io/2017/09/14/the-ultimate-guide-to-writing-a-go-tool/

Tags in Golang

https://medium.com/golangspec/tags-in-golang-3e5db0b8ef3e

Go Tags explained

https://flaviocopes.com/go-tags/