O'Reilly logo

Go Standard Library Cookbook by Radomir Sohlich

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to do it...

  1. Open the console and create the folder chapter11/recipe06.
  2. Navigate to the directory.
  3. Create the file structtags.go with the following content:
        package main        import (          "fmt"          "reflect"        )        type Person struct {          Name string `json:"p_name" bson:"pName"`          Age int `json:"p_age" bson:"pAge"`        }        func main() {          f := &Person{"Tom", 30}          describe(f)        }        func describe(f interface{}) {          val := reflect.TypeOf(f).Elem()          for i := 0; i < val.NumField(); i++ {            typeF := val.Field(i)            fieldName := typeF.Name            jsonTag := typeF.Tag.Get("json")            bsonTag := typeF.Tag.Get("bson")            fmt.Printf("Field : %s jsonTag: %s bsonTag: %s\n",                       fieldName, jsonTag, bsonTag)          }        }
  1. Execute the code by go run structtags.go.
  2. See the output in the Terminal:

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required