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 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献