Deep dive into Go Struct Tags

Growing as a Go developer: From dark age to advance language features

type Todo struct {
ID int `json:"id"`
Content string `json:"content"`
Timestamp int64 `json:"ts"`
}
type Todo struct {
ID int `db:"id"`
Content string `db:"content"`
Timestamp int64 `db:"ts"`
}

Unleashing reflection in Go

ID id 1
Content content Chop carrots
Timestamp ts 1257894000
todo := NewTodo(1, "Chop carrots", time.Now().Unix())
v := reflect.ValueOf(todo)
v.Kind() == reflect.Ptr 
v.Kind() == reflect.Struct
v = v.Elem()
t := v.Type()
for i := 0; i < v.NumField(); i++
fmt.Println(t.Field(i).Name,
t.Field(i).Tag.Get("db"),
v.Field(i).Interface())

Summarizing learning

Where to go from here?

  • Since working with types at runtime circles around reflection, it is highly recommended to look into the reflect package.
  • Internals of encoding/json package. Especially the unexported typeFields function.

References

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store