type Person struct { Name string `json:"name" validate:"required"` Age int `json:"age"` } func main() { p := Person{Name: "John", Age: 30} // get the tags for the "Name" field nameField, _ := reflect.TypeOf(p).FieldByName("Name") nameTags := nameField.Tag // get the value of the "json" tag jsonTag := nameTags.Get("json") fmt.Println(jsonTag) // outputs "name" // get the value of the "validate" tag validateTag := nameTags.Get("validate") fmt.Println(validateTag) // outputs "required" }
type Product struct { Name string `json:"name"` PriceCents int `json:"price_cents"` DiscountRate float64 `json:"discount_rate"` } func main() { // create an instance of the struct prod := Product{ Name: "Widget", PriceCents: 2000, DiscountRate: 0.1, } // get the tags for the "PriceCents" field priceField, _ := reflect.TypeOf(prod).FieldByName("PriceCents") priceTags := priceField.Tag // get the value of the "json" tag priceJsonTag := priceTags.Get("json") fmt.Println(priceJsonTag) // outputs "price_cents" // get the value of the "xml" tag (this will return an empty string, since the "xml" tag is not defined) priceXmlTag := priceTags.Get("xml") fmt.Println(priceXmlTag) // outputs "" }In this example, we define a struct `Product` with three fields, `Name`, `PriceCents`, and `DiscountRate`. We use reflection to retrieve the metadata tags for the `PriceCents` field, and then use the `Get` method of `StructTag` to extract the value of the `json` tag. We also attempt to extract the value of a tag that does not exist, and observe that an empty string is returned. This code example uses the `reflect` package of the standard library.