How do I know the fields I can access from the reply
object/interface? I tried reflection but it seems you have to know the field name first. What if I need to know all the fields available to me?
// Do sends a command to the server and returns the received reply.
Do(commandName string, args ...interface{}) (reply interface{}, err error)
You can use the
reflect.TypeOf()
function to obtain areflect.Type
type descriptor. From there, you can list fields of the dynamic value stored in the interface.Example:
Output:
The result of a
Type.Field()
call is areflect.StructField
value which is astruct
, containing the name of the field among other things:If you also want the values of the fields, you may use
reflect.ValueOf()
to obtain areflect.Value()
, and then you may useValue.Field()
orValue.FieldByName()
:Output:
Try it on the Go Playground.
Note: often a pointer to struct is wrapped in an interface. In such cases you may use
Type.Elem()
andValue.Elem()
to "navigate" to the pointed type or value:If you don't know whether it's a pointer or not, you can check it with
Type.Kind()
andValue.Kind()
, comparing the result withreflect.Ptr
:Try this variant on the Go Playground.
For a detailed introduction to Go's reflection, read the blog post: The Laws of Reflection.