Created
February 6, 2023 15:27
-
-
Save wxk6b1203/81f7ed5d700e31f5e1b1c8b640f66874 to your computer and use it in GitHub Desktop.
Golang get struct fields
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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