dqsvnsad79721 2016-12-24 01:17
浏览 223
已采纳

在reflect.MakeFunc中返回错误值

I am trying to create an return a function in golang which has a return type of (SomeStruct, error) (standard error interface)

fn := func (args []reflect.Value) []reflect.Value {
    database := mongoConnectorInstance.GetDatabase()
    defer database.Session.Close()

    selector := bson.M{
        field : args[0].Interface(),
    }

    newValue := reflect.New(fieldFunctionValue.Type().Out(0))
    newValueInterface := newValue.Interface()
    fmt.Println(reflect.TypeOf(newValueInterface))

    err := database.C(collection).Find(selector).One(newValueInterface)

    secondValue := reflect.ValueOf(err)
    return []reflect.Value {
        newValue.Elem(),
        secondValue,
    }
}

resultFunctionValue := reflect.MakeFunc(fieldFunctionValue.Type(), fn)

If err returned by .One function is null, I get address pointer error on this line, internally in golang :

panic("reflect: function created by MakeFunc using " + funcName(f) +
                    " returned wrong type: have " +
                    out[i].typ.String() + " for " + typ.String())

I have tried to change the line of secondValue assignment to :

secondValue := reflect.ValueOf((error)(nil)) 

in the case where err == nil, however the problem did not go away.

If I create a dummy error struct that implements the interface error and return that, ignoring error return value has to be nil when it is really nil, then it complains that the return value by the function made by makeFunc is incorrect

Can you think of a way to solve this problem? (Except wrapping the error in a struct, and changing the return type to that struct instead )

  • 写回答

1条回答 默认 最新

  • dqp4933 2016-12-24 04:33
    关注

    Use this line to set secondValue:

    secondValue := reflect.ValueOf(&err).Elem()
    

    The call ValueOf(&err) returns a reflect.Value with type *error. Calling Elem() on that value returns a reflect.Value with type error.

    The call ValueOf(err) returns a reflect.Value with the type of the concrete value of err or an invalid reflect.Value if there is no concrete value in err (err == nil). Either way, the returned reflect.Value does not have type error.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?