dongshi2458 2015-06-04 19:23
浏览 88
已采纳

去反射一下。 如何返回err = nil作为reflect.Value?

How to return a err=nil as reflect.Value? I need to write a swap function to use with reflect.MakeFunc().

//my swap implementation, that call the original function and cache results
func swapFunc(ins []reflect.Value) []reflect.Value {
    //After cache the first return (Offer) of function FindBestOffer(int)(Offer,bool,error),
    //i need to return the best Offer cached and default values 
    //for the two other returns (bool=true, err=nil)

    outs := make([]reflect.Value, 3) //mock cache return

    outs[0] = reflect.ValueOf(Offer{10, "cached offer", 20})
    outs[1] = reflect.ValueOf(true)
    outs[2] = reflect.ValueOf(nil).Elem() // --> Doesn't work!

    return outs
}

Go Playground full example

  • 写回答

2条回答 默认 最新

  • douqing0713 2015-06-04 19:46
    关注

    It's tricky, you have to use reflect.Zero:

    out[2] = reflect.Zero(reflect.TypeOf((*error)(nil)).Elem())
    

    <kbd>play</kbd>

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 银河麒麟操作系统无法使用U盘
  • ¥100 寻找:光电二极管电路设计服务
  • ¥15 YOLOv5改进后的结构图
  • ¥15 全志v3s怎么设置高速时钟,使用的荔枝派zero开发板,串口2需要921600的波特率
  • ¥15 关于#单片机#的问题:Lora通讯模块hc-14电路图求内部原理图
  • ¥50 esp32 wroom 32e 芯片解锁
  • ¥15 bywave配置文件写入失败
  • ¥20 基于Simulink的ZPW2000轨道电路仿真
  • ¥15 pycharm找不到在环境装好的opencv-python
  • ¥15 在不同的执行界面调用同一个页面