Go 在reflect.MakeFunc中返回错误值
我试图在golang中创建一个返回函数,其返回类型为(SomeStruct,error)(标准错误接口) 如果Go 在reflect.MakeFunc中返回错误值,go,reflection,Go,Reflection,我试图在golang中创建一个返回函数,其返回类型为(SomeStruct,error)(标准错误接口) 如果.One函数返回的err为null,则我在这一行中得到地址指针错误,在golang内部: panic("reflect: function created by MakeFunc using " + funcName(f) + " returned wrong type: have " + out[i].ty
.One
函数返回的err为null,则我在这一行中得到地址指针错误,在golang内部:
panic("reflect: function created by MakeFunc using " + funcName(f) +
" returned wrong type: have " +
out[i].typ.String() + " for " + typ.String())
我已尝试将secondValue赋值行更改为:
secondValue := reflect.ValueOf((error)(nil))
然而,在err==nil
的情况下,问题并没有消失
如果我创建了一个实现接口错误的伪错误结构并返回该错误,那么忽略错误返回值必须是nil,而实际上是nil,那么它会抱怨makeFunc函数的返回值不正确
你能想出解决这个问题的办法吗?(除了将错误包装到结构中,并将返回类型改为该结构之外)使用此行设置
secondValue
:
secondValue := reflect.ValueOf(&err).Elem()
调用ValueOf(&err)
返回类型为*error
的reflect.Value
。对该值调用Elem()
将返回类型为error
的reflect.value
调用
ValueOf(err)
返回具体值类型为err
的reflect.Value
,或者如果err
中没有具体值,则返回无效的reflect.Value
(err==nil
)。无论哪种方式,返回的reflect.Value
没有类型error
我为没有想到这个而感到羞愧。谢谢
secondValue := reflect.ValueOf(&err).Elem()