Skip to content

Instantly share code, notes, and snippets.

@scottcagno
Created August 4, 2016 20:57
Show Gist options
  • Select an option

  • Save scottcagno/00a10618d966f8c7a397aef113ef3851 to your computer and use it in GitHub Desktop.

Select an option

Save scottcagno/00a10618d966f8c7a397aef113ef3851 to your computer and use it in GitHub Desktop.
Get Struct Fields From Struct
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