Created
August 4, 2016 20:57
-
-
Save scottcagno/00a10618d966f8c7a397aef113ef3851 to your computer and use it in GitHub Desktop.
Get Struct Fields From Struct
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" | |
| "reflect" | |
| ) | |
| type T struct { | |
| Id int | |
| Name string | |
| Email string | |
| Query func() | |
| Data []byte | |
| } | |
| func main() { | |
| for name, mtype := range StructFields(&T{Query: func() { fmt.Println("foobar") }, Data: []byte{1, 2, 3}}) { | |
| fmt.Printf("Name: %s, Type %s, Size %d\n", name, mtype, mtype.Size()) | |
| } | |
| } | |
| func StructFields(m interface{}) map[string]reflect.Type { | |
| typ := reflect.TypeOf(m) | |
| if typ.Kind() == reflect.Ptr { | |
| typ = typ.Elem() | |
| } | |
| flds := make(map[string]reflect.Type) | |
| if typ.Kind() != reflect.Struct { | |
| fmt.Printf("%v type can't have attributes inspected\n", typ.Kind()) | |
| return flds | |
| } | |
| for i := 0; i < typ.NumField(); i++ { | |
| p := typ.Field(i) | |
| if !p.Anonymous { | |
| flds[p.Name] = p.Type | |
| } | |
| } | |
| return flds | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment