Skip to content

Latest commit

 

History

History
37 lines (26 loc) · 692 Bytes

golang-reflection-get-tag-from-struct-field.md

File metadata and controls

37 lines (26 loc) · 692 Bytes

如何获取结构中的Tag字符串

stackoverflow连接

使用reflect这个包可以读取,例子如下:

package main

import (
	"fmt"
	"reflect"
)

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

func main() {
	user := &User{"John Doe The Fourth", 20}

	field, ok := reflect.TypeOf(user).Elem().FieldByName("Name")
	if !ok {
		panic("Field not found")
	}
	fmt.Println(getStructTag(field))
}

func getStructTag(f reflect.StructField) string {
	return string(f.Tag)
}

在线连接