繁体   English   中英

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

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

如何返回err = nil作为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
}

转到Playground完整示例

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

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

定义类型的nil错误也可以...

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

只是出于好奇。 去操场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM