From the docs
func (v Value) Elem() Value
Elem returns the value that the interface v contains or that the pointer v points to. It panics if v's Kind is not Interface or Ptr. It returns the zero Value if v is nil.
func Indirect(v Value) Value
Indirect returns the value that v points to. If v is a nil pointer, Indirect returns a zero Value. If v is not a pointer, Indirect returns v.
So can I safely assume the following?
reflect.Indirect(reflect.ValueOf(someX)) === reflect.ValueOf(someX).Elem().
Is Indirect method just a convenience method for the right hand side of the above?
The reflect. Indirect() Function in Golang is used to get the value that v points to, i.e., If v is a nil pointer, Indirect returns a zero Value. If v is not a pointer, Indirect returns v. To access this function, one needs to imports the reflect package in the program.
Elem() Function in Golang is used to get the value that the interface v contains or that the pointer v points to. To access this function, one needs to imports the reflect package in the program.
Reflection in Go is a form of metaprogramming. Reflection allows us to examine types at runtime. It also provides the ability to examine, modify, and create variables, functions, and structs at runtime. The Go reflect package gives you features to inspect and manipulate an object at runtime.
The reflect. ValueOf() Function in Golang is used to get the new Value initialized to the concrete value stored in the interface i. To access this function, one needs to imports the reflect package in the program. Syntax: func ValueOf(i interface{}) Value.
If a reflect.Value
is a pointer, then v.Elem()
is equivalent to reflect.Indirect(v)
. If it is not a pointer, then they are not equivalent:
reflect.Indirect(v)
will return the same value, while v.Elem()
will return the contained dynamic value.v.Elem()
will panic.The reflect.Indirect
helper is intended for cases where you want to accept either a particular type, or a pointer to that type. One example is the database/sql
conversion routines: by using reflect.Indirect
, it can use the same code paths to handle the various types and pointers to those types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With