在反射包中,golang中的Elem和Indirect有什么区别?

huangapple go评论84阅读模式
英文:

golang - Elem Vs Indirect in the reflect package

问题

从文档中可以看到:

func (v Value) Elem() Value

Elem方法返回接口v包含的值或指针v指向的值。如果v的类型不是Interface或Ptr,它会引发panic。如果v为nil,则返回零值Value。

func Indirect(v Value) Value

Indirect方法返回v指向的值。如果v是nil指针,Indirect返回零值Value。如果v不是指针,Indirect返回v本身。

所以我可以安全地假设以下内容吗?

reflect.Indirect(reflect.ValueOf(someX)) === reflect.ValueOf(someX).Elem()

Indirect方法只是上述右侧的便利方法吗?

英文:

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?

答案1

得分: 26

如果reflect.Value是一个指针,那么v.Elem()等同于reflect.Indirect(v)。如果它不是一个指针,那么它们就不等价:

  • 如果值是一个接口,那么reflect.Indirect(v)将返回相同的值,而v.Elem()将返回包含的动态值。
  • 如果值是其他类型,那么v.Elem()将引发恐慌。

reflect.Indirect助手函数用于在您想要接受特定类型或该类型的指针的情况下。一个例子是database/sql的转换例程:通过使用reflect.Indirect,它可以使用相同的代码路径来处理各种类型和指向这些类型的指针。

英文:

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.

huangapple
  • 本文由 发表于 2014年6月20日 08:45:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/24318389.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定