Go 正在将接口{}强制转换为运行时类型中计算的
下面是我需要的示意图示例:Go 正在将接口{}强制转换为运行时类型中计算的,go,Go,下面是我需要的示意图示例: func decode(data []byte, target interface{}) (interface{}, error) { decoded := target.(reflect.TypeOf(target)) // pseudocode err := json.Unmarshal(data, &decoded) ... 我发现了几个类似的问题,但所有的解决方案都是关于通过target.(键入)切换的。这不是我寻找的最佳解决
func decode(data []byte, target interface{}) (interface{}, error) {
decoded := target.(reflect.TypeOf(target)) // pseudocode
err := json.Unmarshal(data, &decoded)
...
我发现了几个类似的问题,但所有的解决方案都是关于通过target.(键入)
切换的。这不是我寻找的最佳解决方案
我还通过反思找到了解决方案:
decoded := reflect.ValueOf(target).Convert(reflect.TypeOf(target))
// fmt.Printf("%T", decoded) == reflect.Value
但我不明白如何从reflect.Value
获取struct,将其传递给json.Unmarshal
函数
该解码功能将如何使用?
我有多个不同结构的请求。我可以确定应该使用什么结构来解码请求。我在请求类型和结构之间有这样的映射map[RequestMethod]interface{}
原理图版本如下所示:
func hydrate(data []byte) (interface{}, error) {
var base baseResponse
if err := json.Unmarshal(data, &base); err != nil {
return nil, err
}
target, ok := methodsMap[Method(base.Method)]
if !ok {
return nil, errors.New("Trying to hydrate data with unknown method: " + base.Method)
}
decoded, err := decode(data, target) // Expected target type.
增加:
如果我们将target
传递给json.Unmarshal
而不强制转换为它的类型,我们将获得map
。例如:
func decode(data []byte, target interface{}) (interface{}, error) {
err := json.Unmarshal(data, &target)
// fmt.Printf("%T", target) == map[string]interface{} not struct.
解决方案
感谢我们找到的解决方案:
func水合物(数据[]字节)(接口{},错误){
var基响应
if err := json.Unmarshal(data, &base); err != nil {
return nil, err
}
target, ok := methodsMap[Method(base.Method)]
if !ok {
return nil, errors.New("Trying to hydrate data with unknown method: " + base.Method)
}
// Clone request draft struct.
decoded := reflect.New(reflect.ValueOf(target).Type()).Interface()
err := decode(data, decoded)
...
相关链接:
使用以下代码创建草稿结构的副本并将其解组:
t := reflect.TypeOf(methodsMap[Method(base.Method)])
pv := reflect.New(t)
err := json.Unmarshal(p, pv.Interface())
return pv.Elem().Interface(), err // pv.Elem() dereferences ptr
使用以下代码创建草稿结构的副本并将其解组:
t := reflect.TypeOf(methodsMap[Method(base.Method)])
pv := reflect.New(t)
err := json.Unmarshal(p, pv.Interface())
return pv.Elem().Interface(), err // pv.Elem() dereferences ptr
这似乎非常不必要。只需将
target
传递给json.Unmarshal
就可以了。告诉我们如何调用decode()
函数。很可能您传递了一个错误的值。和的可能重复。@AlexBor如果您阅读了我的其他答案:您不需要将其转换为任何内容。错误之处在于调用decode()
函数:您必须向其传递指向结构的指针。在decode()
内部,您只需传递接口{}
value tojson.Unmarshal()
。这似乎非常不必要。只需将target
传递给json.Unmarshal
就可以了。告诉我们如何调用此decode()
函数。很可能您传递了一个错误的值。和的可能重复。@AlexBor如果您阅读了我的其他答案:您不需要将其转换为任何内容。错误之处在于调用decode()
函数:您必须向其传递指向结构的指针。在decode()
内部,您只需传递接口{}
value tojson.Unmarshal()
@AlexBor省略最后的类型断言。我在那里使用它是因为我后来使用了它。只需使用reflect.New(…).Interface()
。