How to Read Struct Tags with Reflection in Go

Read Go struct tags at runtime using reflect.TypeOf to get the struct type and Field.Tag.Get to extract specific tag values.

Use the reflect package to get the Struct type of your struct, then call Field(i).Tag on the desired field index to retrieve the tag string.

package main

import (
	"fmt"
	"reflect"
)

type User struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

func main() {
	t := reflect.TypeOf(User{})
	field, _ := t.FieldByName("Name")
	tag := field.Tag.Get("json")
	fmt.Println(tag) // Output: name
}