Created
April 26, 2013 17:45
-
-
Save justincase/5469009 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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
@mrdulin just put in a guard to check f.PkgPath, since it's only populated for unexported fields,
f.PkgPath == ""
will only be true for exported fields, so you can avoid panics when trying to process unexported fields.