package main
import (
"fmt"
"reflect"
)
type User struct {
Name string
Age int
Password string
}
func GetFieldNames(s interface{}) []string {
t := reflect.TypeOf(s)
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
if kind := t.Kind(); kind != reflect.Struct {
fmt.Printf("not a struct kind: %s", kind)
return nil
}
var ret []string
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
ret = append(ret, field.Name)
}
return ret
}
func main() {
u := User{}
fmt.Println(GetFieldNames(u))
fmt.Println(GetFieldNames(&u))
}
At Go Playground: http://play.golang.org/p/6LDoCIKFeH
The function returns a slice of strings. Each is a name of a field. If a pointer is an argument the underlying type's field names are returned. The function ended up in: github.com/orian/utils/reflect. A documentation is browsable at: https://gowalker.org/github.com/orian/utils/reflect.
A short explanation:
- First get a
reflect.Type
of a given arguments
- If
s'
kind is a pointer, get a descriptor of underlying type. - If underlying type is not a struct, return error..
- Iterate over fields, add field names and return the result slice.