Thursday, July 30, 2015

Go: a list of structure field names

package main

import (

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{}
At Go Playground:
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: A documentation is browsable at:
A short explanation:
  • First get a reflect.Type of a given argument s
  • 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.

No comments:

Post a Comment