[英]How can I use reflect.Value.Call() with a nil input?
I want to invoke a function in Go, using reflect.Value.Call on a method value, and pass nil as a parameter. 我想在Go中调用一个函数,在方法值上使用reflect.Value.Call,并将nil作为参数传递。 See the code below for an illustration. 请参阅下面的代码以获取说明。
I have tried using reflect.ValueOf(nil)
and reflect.Value{}
in the input array, but the first panics because nil has no value; 我尝试在输入数组中使用reflect.ValueOf(nil)
和reflect.Value{}
,但是第一次恐慌是因为nil没有值; the second panics when I pass it to Call, because it is a Zero reflect.Value. 当我把它传递给Call时,第二次恐慌,因为它是一个Zero reflect.Value。
Note that, as the code illustrates, it is certainly possible to pass nil to a function without reflection, including when that argument is the receiver. 请注意,正如代码所示,当然可以将nil传递给没有反射的函数,包括当该参数是接收器时。 The question is: Is it possible to invoke a func using reflect.Value.Call, passing one of those parameters as nil? 问题是: 是否可以使用reflect.Value.Call调用func,将其中一个参数传递为nil?
You can build and run the code below at: http://play.golang.org/p/x9NXMDHWdM 您可以在http://play.golang.org/p/x9NXMDHWdM上构建并运行以下代码
package main
import "reflect"
type Thing struct{}
var (
thingPointer = &Thing{}
typ = reflect.TypeOf(thingPointer)
)
func (t *Thing) DoSomething() {
if t == nil {
println("t was nil")
} else {
println("t was not nil")
}
}
func normalInvokation() {
thingPointer.DoSomething()
// prints "t was not nil"
t := thingPointer
t = nil
t.DoSomething()
// prints "t was nil"
}
func reflectCallNonNil() {
m, _ := typ.MethodByName("DoSomething")
f := m.Func
f.Call([]reflect.Value{reflect.ValueOf(&Thing{})})
// prints "t was not nil"
}
func reflectCallNil() {
// m, _ := typ.MethodByName("DoSomething")
// f := m.Func
// f.Call(???)
// how can I use f.Call to print "t was nil" ?
}
func main() {
normalInvokation()
reflectCallNonNil()
reflectCallNil()
}
One option is to simply tell reflect
that you mean a nil pointer to Thing
: 一种选择是简单地告诉reflect
你的意思是指向Thing
的nil指针:
func reflectCallNonNil() {
m, _ := typ.MethodByName("DoSomething")
f := m.Func
f.Call([]reflect.Value{reflect.ValueOf((*Thing)(nil))})
}
Also, you can use reflect.Zero
which gives you a "zero value" for a type. 此外,您可以使用reflect.Zero
,它为您提供类型的“零值”。 So nil in this context is the zero value of pointer to Thing
. 所以这个上下文中的零是指针Thing
的零值。
Thus, doing this will work: 因此,这样做将起作用:
func reflectCallNil() {
m, _ := typ.MethodByName("DoSomething")
f := m.Func
f.Call([]reflect.Value{reflect.Zero(reflect.TypeOf(&Thing{}))})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.