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

去反射一下。 如何返回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())
    

    play

    打赏 评论
  • douliang7068 2015-06-04 20:14

    Defining a typed nil error works too...

    var err error = nil
    outs[2] = reflect.ValueOf(&err).Elem()
    

    Just out of curiosity. Go Playground

    打赏 评论

相关推荐 更多相似问题