Skip to content

Instantly share code, notes, and snippets.

@wxk6b1203
Created February 6, 2023 15:27
Show Gist options
  • Save wxk6b1203/81f7ed5d700e31f5e1b1c8b640f66874 to your computer and use it in GitHub Desktop.
Save wxk6b1203/81f7ed5d700e31f5e1b1c8b640f66874 to your computer and use it in GitHub Desktop.
Golang get struct fields
package main
import "fmt"
func GetStructTags(s interface{}, tag string) map[string]string {
t := reflect.TypeOf(s)
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
if t.Kind() != reflect.Struct {
return nil
}
m := make(map[string]string)
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
m[f.Name] = f.Tag.Get(tag)
}
return m
}
type Test struct {
TestCase `ta:"tc"`
}
func main() {
t := &Test{}
vals := GetStructTags(t, "tc")
for _, v := range vals {
fmt.Println(v)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment