Skip to content

Instantly share code, notes, and snippets.

@kamal-github
Forked from justincase/gist:5469009
Created September 19, 2017 10:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamal-github/95f44c7fe22225c7b5cd59bce400355a to your computer and use it in GitHub Desktop.
Save kamal-github/95f44c7fe22225c7b5cd59bce400355a to your computer and use it in GitHub Desktop.
Print struct with field names and values. From http://blog.golang.org/2011/09/laws-of-reflection.html
type T struct {
A int
B string
}
t := T{23, "skidoo"}
s := reflect.ValueOf(&t).Elem()
typeOfT := s.Type()
for i := 0; i < s.NumField(); i++ {
f := s.Field(i)
fmt.Printf("%d: %s %s = %v\n", i,
typeOfT.Field(i).Name, f.Type(), f.Interface())
}
// The output of this program is
//
// 0: A int = 23
// 1: B string = skidoo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment