如何使用Golang的反射实例化nil错误? [英] How can I instantiate a nil error using Golang's reflect?
问题描述
我正在使用reflect.MakeFunc编写一个函数.该函数可以返回错误.成功后,我希望它为错误类型的返回值返回nil.如何使用反射来做到这一点?目前,我有这个:
I am writing a function using reflect.MakeFunc. That function can return an error. When it succeeds, I want it to return nil for its error-typed return value. How can I do that using reflect? Currently I have this:
package main
import (
"fmt"
"reflect"
"errors"
)
func main() {
fmt.Println("Hello, playground")
f := func() error {return nil}
fn := reflect.MakeFunc(reflect.TypeOf(f), func(args []reflect.Value) []reflect.Value {
return []reflect.Value{reflect.New(reflect.TypeOf(errors.New("")))}
}).Interface().(func() error)
fmt.Printf("err: %v", fn())
}
我得到 panic:反映:由MakeFunc使用闭包创建的函数返回了错误的类型:具有** errors.errorString错误
.我还尝试在 reflect.New(reflect.TypeOf(errors.New(")))
之后添加 .Elem()
,但出现了 panic:反映:由MakeFunc使用闭包创建的函数返回了错误的类型:具有* errors.errorString表示错误
.我尝试了 .Elem().Elem()
,但出现了分段错误.
I get panic: reflect: function created by MakeFunc using closure returned wrong type: have **errors.errorString for error
. I also tried adding a .Elem()
after reflect.New(reflect.TypeOf(errors.New("")))
, but I got panic: reflect: function created by MakeFunc using closure returned wrong type: have *errors.errorString for error
. I tried .Elem().Elem()
, and I got a segmentation fault.
如何获取代表nil错误的reflect.Value?
How can I get a reflect.Value representing a nil error?
推荐答案
使用以下内容:
var nilError = reflect.Zero(reflect.TypeOf((*error)(nil)).Elem())
func main() {
fmt.Println("Hello, playground")
f := func() error { return nil }
fn := reflect.MakeFunc(reflect.TypeOf(f), func(args []reflect.Value) []reflect.Value {
return []reflect.Value{nilError}
}).Interface().(func() error)
fmt.Printf("err: %v", fn())
}
让我们分解一下.第一步是为 error
获取一个 reflect.Type
: reflect.TypeOf((* error)(nil)).Elem()
.更简单的 reflect.TypeOf((error)(nil))
不起作用,因为参数的具体值为 nil
.没有 nil
的类型,也不是我们想要的类型.解决方法是传递一个指向 error
的指针,然后在该类型上调用 Elem()
以获得 error的
relfect.Type
.
Let's break this down. The first step is to get a reflect.Type
for error
: reflect.TypeOf((*error)(nil)).Elem()
. The simpler reflect.TypeOf((error)(nil))
does not work because the concrete value of the argument is nil
. There's no type for nil
and it's not the type we want anyway. The workaround is to pass a pointer to error
and then call Elem()
on the type to get the relfect.Type
for error
.
第二步是为类型创建一个零值.
The second step is to create a zero value for the type.
这篇关于如何使用Golang的反射实例化nil错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!