我想在 Go 中調(diào)用一個函數(shù),在方法值上使用reflect.Value.Call,并將 nil 作為參數(shù)傳遞。有關(guān)說明,請參閱下面的代碼。我曾嘗試在輸入數(shù)組中使用reflect.ValueOf(nil)and reflect.Value{},但第一次出現(xiàn)恐慌,因為 nil 沒有價值;當我將它傳遞給 Call 時,第二個恐慌,因為它是一個零反射值。請注意,正如代碼所示,當然可以在沒有反射的情況下將 nil 傳遞給函數(shù),包括當該參數(shù)是接收者時。問題是:是否可以使用reflect.Value.Call 調(diào)用func,將這些參數(shù)之一作為nil 傳遞?您可以在以下位置構(gòu)建和運行代碼:http : //play.golang.org/p/x9NXMDHWdMpackage mainimport "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()}
- 1 回答
- 0 關(guān)注
- 227 瀏覽
添加回答
舉報
0/150
提交
取消