go - 在 reflect.MakeFunc 中返回错误值

标签 go reflection

我正在尝试在 golang 中创建一个返回类型为 (SomeStruct, 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)

如果 .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 的情况下,问题并没有消失。

如果我创建一个实现接口(interface)错误的虚拟错误结构并返回它,忽略错误返回值必须为 nil 当它真的是 nil 时,它会提示 makeFunc 函数的返回值是不正确

你能想出办法解决这个问题吗? (除了将错误包装在结构中,并将返回类型更改为该结构)

最佳答案

使用这一行设置secondValue:

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

调用 ValueOf(&err) 返回类型为 *errorreflect.Value。对该值调用 Elem() 会返回类型为 errorreflect.Value

调用ValueOf(err)返回一个reflect.Value,其类型为err的具体值或一个无效的 reflect.Value 如果 err 中没有具体值(err == nil)。无论哪种方式,返回的 reflect.Value 都没有类型 error

关于go - 在 reflect.MakeFunc 中返回错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41309499/

相关文章:

go - 你能调用 gofmt 来格式化你从编写它的 Go 代码内部编写的文件吗?

pointers - 指针变量的地址何时更改?

java - 替代 String.equals 进行多次比较(无枚举)

string - 在Go中合并存储在 channel 上的多个 map (对相同键的值求和)

戈朗 : is a mutex required for a package-scoped variable with read-only access?

go - 如何强制 Goland 每次都运行测试?

c# - 动态检测基类类型对象中包装了哪个子类

optimization - 如何在 Golang 中获取指向任何数据类型值的字节指针?

scala - 在 Scala 的类字段中查找合成成员

reflection - 如何动态测试 Self 类型和不相关的类型