【发布时间】:2015-11-04 19:31:27
【问题描述】:
我尝试在 go 中编写简单的消息协议,但遇到了问题。我有很多消息类型,我想要一个这样的字典来处理消息:
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
}
它工作正常,但是当我使用 GetValueByTypeId 实例化消息并尝试将 json 解组到其中时 - 我收到的是 map[string]interface 而不是我的消息。 我做了一个简单的例子来重现这个问题:
【问题讨论】:
-
在您的示例中,您使用
reflect.Zero而不是reflect.New作为destination3。更改为New即可解决问题。但在你的问题中是New,所以我不确定发生了什么。 -
我用
New重新制作了示例,但结果与play.golang.org/p/Ts0jvApwtY 相同 -
我没有提到
val := reflection.New(type).Interface(); json.Unmarshal(data, val)有效,但我不需要指针,而是值本身。在这种情况下,我无法进行转换return *val- 因为错误invalid indirect
标签: json reflection go unmarshalling