Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@justincase
Created April 26, 2013 17:45
Show Gist options
  • Star 67 You must be signed in to star a gist
  • Fork 15 You must be signed in to fork a gist
  • Save justincase/5469009 to your computer and use it in GitHub Desktop.
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
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
@hygull
Copy link

hygull commented Dec 17, 2016

Nice explanatory code for extracting the details of structure's field name, its value and type.

@mfrazi
Copy link

mfrazi commented Dec 27, 2017

well played, thank you :)

@helmutkemper
Copy link

thank you :)

@swapnil-pandey
Copy link

panic: reflect: call of reflect.Value.NumField on interface Value

It gives me this error.
My struct is defined as :

type bundle struct {
valnode *Node
tree *tree
}

@OddCN
Copy link

OddCN commented Mar 13, 2018

awesome guy!

@jeremysnyt
Copy link

Excellent - Clean, succinct

@jamesajones
Copy link

Spent several hours before finding this Thanks

@xgz123
Copy link

xgz123 commented Jul 17, 2018

f.Interface undefined..

@eddieowens
Copy link

eddieowens commented Sep 30, 2018

@xgz123 you're probably calling reflect.TypeOf(struct) rather than reflect.ValueOf(struct). Calling Field(i) on a Type returns a StructField which doesn't have the Interface method. Calling reflect.ValueOf(struct).Field(i) returns a Value which does have the Interface method.

@mrdulin
Copy link

mrdulin commented Oct 17, 2019

f.Interface() only works for the struct type which has public fields.

@seyedmmousavi
Copy link

Simpler way from @motyar at here
fmt.Printf("%+v\n", myStructInstance)

@yuta-tkd
Copy link

yuta-tkd commented Apr 3, 2020

This code worked.

v := reflect.ValueOf(structValue)
t := v.Type()
for i := 0; i < t.NumField(); i++ {
	name := t.Field(i).Name
	value := v.FieldByName(name).Interface()
}

@ScarletTanager
Copy link

@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.

@motyar
Copy link

motyar commented May 3, 2020

Simpler way from @motyar at here
fmt.Printf("%+v\n", myStructInstance)

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment