Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang - Elem Vs Indirect in the reflect package

Tags:

go

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?

like image 901
sat Avatar asked Jun 20 '14 00:06

sat


People also ask

What is reflect indirect?

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.

What is $[ elem in Golang?

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.

What is reflect package in Golang?

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.

What ValueOf reflect?

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.


1 Answers

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:

  • If the value is an interface then reflect.Indirect(v) will return the same value, while v.Elem() will return the contained dynamic value.
  • If the value is something else, then 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.

like image 198
James Henstridge Avatar answered Sep 30 '22 20:09

James Henstridge