Golang通过反射将nil值作为接口传递 [英] Golang pass nil value as an interface through reflection
问题描述
我有一个带有接口参数的函数:
I have a function with interface argument:
func f(e error) {
if e == nil {
fmt.Println("YEY! NIL") // how to get here?
} else {
fmt.Println("NOT NIL :(")
}
}
如何通过 reflect
向其传递nil值,以使其通过 == nil
检查?
How do I pass it a nil value via reflect
so that it passes == nil
check?
方法1:
func main() {
rf := reflect.ValueOf(f)
nilArg := reflect.Zero(reflect.TypeOf((error)(nil))) // panic: reflect: Zero(nil)
rf.Call([]reflect.Value{nilArg})
}
方法2:
type MyError struct{}
func (e MyError) Error() string {
return ""
}
func main() {
rf := reflect.ValueOf(f)
nilArg := reflect.Zero(reflect.TypeOf(&MyError{})) // NOT NIL :(
rf.Call([]reflect.Value{nilArg})
}
由于 https://golang.org/doc/faq#nil_error,第二种方法不起作用
游乐场: https://play.golang.org/p/V0bMSPcCKI >
推荐答案
使用以下代码创建 nilArg
:
nilArg := reflect.Zero(reflect.TypeOf((*error)(nil)).Elem())
问题中的第一种方法不起作用,因为表达式 reflect.TypeOf((error)(nil))
返回 nil
.nil接口值的具体类型为nil.
The first approach in the question does not work because the expression reflect.TypeOf((error)(nil))
returns nil
. The concrete type of a nil interface value is nil.
诀窍是将非接口值传递给 reflect.TypeOf()
并使用反射方法从此处获取所需的 reflect.Type
.在这个答案中,我将 * error
传递给 reflect.TypeOf()
,然后对结果调用 Elem
以获取 reflect.输入
以表示错误
.
The trick is to pass a non-interface value to reflect.TypeOf()
and use reflect methods to get the desired reflect.Type
from there. In this answer, I pass a *error
to reflect.TypeOf()
and call Elem
on the result to get the reflect.Type
for error
.
这篇关于Golang通过反射将nil值作为接口传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!