douhong4452 2014-09-06 13:11
浏览 322
已采纳

如何在无输入的情况下使用reflect.Value.Call()?

I want to invoke a function in Go, using reflect.Value.Call on a method value, and pass nil as a parameter. 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; the second panics when I pass it to Call, because it is a 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. The question is: Is it possible to invoke a func using reflect.Value.Call, passing one of those parameters as nil?

You can build and run the code below at: 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()
}
  • 写回答

1条回答 默认 最新

  • doude4924 2014-09-06 13:18
    关注

    One option is to simply tell reflect that you mean a nil pointer to Thing:

    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. So nil in this context is the zero value of pointer to Thing.

    Thus, doing this will work:

    func reflectCallNil() {
        m, _ := typ.MethodByName("DoSomething")
        f := m.Func
        f.Call([]reflect.Value{reflect.Zero(reflect.TypeOf(&Thing{}))})
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)