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

huangapple go评论92阅读模式
英文:

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

问题

如何将err=nil作为reflect.Value返回?我需要编写一个与reflect.MakeFunc()一起使用的swap函数。

//我的swap实现,调用原始函数并缓存结果
func swapFunc(ins []reflect.Value) []reflect.Value {
//在缓存函数FindBestOffer(int)(Offer,bool,error)的第一个返回值(Offer)之后,
//我需要返回缓存的最佳Offer和默认值
//对于另外两个返回值(bool=true, err=nil)

outs := make([]reflect.Value, 3) //模拟缓存返回值

outs[0] = reflect.ValueOf(Offer{10, "cached offer", 20})
outs[1] = reflect.ValueOf(true)
outs[2] = reflect.Zero(reflect.TypeOf((*error)(nil)).Elem()) // --> 这样做可以工作!

return outs

}

完整的Go Playground示例

英文:

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

答案1

得分: 2

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

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

只是出于好奇。

Go Playground

英文:

Defining a typed nil error works too...

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

Just out of curiosity.
Go Playground

答案2

得分: 1

这是一个棘手的问题,你需要使用reflect.Zero

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

play

英文:

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

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

<kbd>play</kbd>

huangapple
  • 本文由 发表于 2015年6月5日 03:23:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/30652392.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定