golang-反射包中的Elem Vs Indirect [英] golang - Elem Vs Indirect in the reflect package
问题描述
来自文档
func(v值)Elem()值
Elem返回接口v包含的值或指针v指向的值.如果v的Kind不是Interface或Ptr,则会感到恐慌.如果v为零,则返回零值.
func间接(v值)值
Indirect返回v指向的值.如果v是nil指针,则Indirect返回零值.如果v不是指针,则Indirect返回v.
那么我可以安全地假设以下内容吗?
reflect.Indirect(reflect.ValueOf(someX))=== reflect.ValueOf(someX).Elem().
间接方法只是上面右侧的一种便捷方法吗?
如果 reflect.Value
是指针,则 v.Elem()
等效于 reflect.Indirect(v)
.如果不是指针,则它们不是等效的:
- 如果该值是接口,则
reflect.Indirect(v)
将返回相同的值,而v.Elem()
将返回所包含的动态值./li> - 如果该值是其他值,则
v.Elem()
会惊慌.
reflect.Indirect
帮助程序用于需要接受特定类型或指向该类型的指针的情况.一个示例是 database/sql
转换例程:通过使用 reflect.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?
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, whilev.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.
这篇关于golang-反射包中的Elem Vs Indirect的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!