去reflect.MakeFunc。如何 return a err=nil as reflect.Value?

Go reflect.MakeFunc. How to return a err=nil as reflect.Value?

如何return a err=nil as reflect.Value?我需要编写一个交换函数以与 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

这很棘手,你必须使用reflect.Zero:

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

play

定义类型化的 nil 错误也有效...

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

只是出于好奇。 Go Playground