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.

Wednesday, July 1, 2015

TIL: clicked element reference in JavaScript console

I had a break from WebDev for around 2 years. I'm rediscovering things now. Today I've learnt: $0
  • Right click on the element of interest in your browser and select 'inspect element'. You should see the browser debugger with the element you clicked on highlighted.
  • The debugger allows you to access the currently selected element in the console as $0 variable.