Skip to content

Instantly share code, notes, and snippets.

@bzon
Last active March 22, 2019 12:09
Show Gist options
  • Save bzon/9eaa38185fa1540c863e8c7cbb8057bd to your computer and use it in GitHub Desktop.
Save bzon/9eaa38185fa1540c863e8c7cbb8057bd to your computer and use it in GitHub Desktop.
Print struct field names and values using Reflection

At some point in your day to day hacking life, getting the Struct fields and values may come in handy.

package main

import (
	"fmt"
	"reflect"
)

type Person struct {
	Name string
	ID   string
}

type Robot struct {
	Person
	IP string
}

func main() {
	p := Person{"john", "12345"}
	r := Robot{p, "1.1.1.1"}

	v := reflect.ValueOf(&r).Elem()

	for i := 0; i < v.NumField(); i++ {
		if v.Field(i).Kind() == reflect.Struct {
			v2 := reflect.ValueOf(v.Field(i).Interface())
			for j := 0; j < v2.NumField(); j++ {
				fmt.Printf("%s.%s %s = %v\n",
					v.Field(i).Type(),
					v2.Type().Field(j).Name,
					v2.Field(j).Type(),
					v2.Field(j).Interface(),
				)
			}
			continue
		}

		fmt.Printf("%s %s = %v\n",
			v.Type().Field(i).Name,
			v.Field(i).Type(),
			v.Field(i).Interface(),
		)
	}
}

Output:

main.Person.Name string = john
main.Person.ID string = 12345
IP string = 1.1.1.1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment