douao1858 2015-08-12 09:20
浏览 85
已采纳

golang无法解析json以创建反射对象

I try to write simple message protocol in go and i've encountered a problem. I have a lot of message types and i want to have a dictionary like this to manipulate with messages:

var dict map[reflect.Type]int = map[reflect.Type]int{
    reflect.TypeOf(DataMessage{}):          1000,
    reflect.TypeOf(TextMessage{}):          1001,
    //....
}

func GetMessageTypeId(value interface{}) int {
    if id, ok := dict[reflect.TypeOf(value)]; ok {
        return id
    } else {
        return -1
    }
}

func GetValueByTypeId(typeId int) interface{} {
    for typeDec, id := range dict {
        if id == typeId {
            return reflect.Zero(typeDec).Interface()
        }
    }
    fmt.Println("Unknown message type", typeId)
    return nil
}

It works fine, but when i instantiate message with GetValueByTypeId and try to unmarshall json into it - i receive map[string]interface instead of my message. I've made simple example to reproduce the problem:

http://play.golang.org/p/QEyDN9vztr

  • 写回答

2条回答 默认 最新

  • dqgxazo4483 2015-08-12 10:13
    关注

    Please read this article: http://research.swtch.com/interfaces, especially the "Memory Optimizations".

    The interface{} by definition consists of two pointers - to method table (e.g. type) and to data it holds. So for

    var destination3 interface{} = reflect.Zero(reflect.TypeOf(Message{})).Interface()
    

    it is empty method table (as interface{} has no methods) and reference to Message{}. Taking reference from it returns the reference to this struct so the unmarhal overwrites it with whatever matches interface{}.

    If the data interface{} variable holds is a pointer itself, then it is optimized in a way that this pointer is used instead creating interface{} structure. So getting reference to it gives the reference to original variable.

    http://play.golang.org/p/KsIS29rUAX

    package main
    
    import "fmt"
    
    func main() {
        var m1 struct{ Data string }
        var m2 interface{}
        var m3 interface{}
    
        m2 = &m1
        m3 = m1
    
        fmt.Printf("&m1=%p m2=%p &m3=%p
    ", &m1, m2, &m3)
    }
    

    In your case, using Zero is equivalent to m3 in the example above. Using New is equivalent to m2.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真