golang - Elem Vs Indirect in the reflect package
Asked Answered
A

1

21

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?

Amuse answered 20/6, 2014 at 0:45 Comment(1)
I have a follow up question to this one in case you know the answer: #52133017Turdine
G
26

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.

Groot answered 20/6, 2014 at 1:3 Comment(1)
I have a follow up question to this one in case you know the answer: #52133017Turdine

© 2022 - 2024 — McMap. All rights reserved.