1 回答
TA贡献1876条经验 获得超5个赞
问题中的方法不起作用,因为嵌入式结构共享字段名称。试试这个方法。
声明一个将游戏类型标识符与相关围棋类型相关联的地图。这只是与解码相关的代码,它知道数百种游戏类型。
var gameTypes = map[int]reflect.Type{
1: reflect.TypeOf(&MatchGame1{}),
2: reflect.TypeOf(&MatchGame2{}),
}
将匹配数据解码为原始消息。使用游戏类型创建匹配数据值并解码为该值。
func decodeMatch(r io.Reader) (*Match, error) {
// Start with match data set to a raw messae.
var raw json.RawMessage
m := &Match{MatchData: &raw}
err := json.NewDecoder(r).Decode(m)
if err != nil {
return nil, err
}
m.MatchData = nil
// We are done if there's no raw message.
if len(raw) == 0 {
return m, nil
}
// Create the required match data value.
t := gameTypes[m.GameType]
if t == nil {
return nil, errors.New("unknown game type")
}
m.MatchData = reflect.New(t.Elem()).Interface()
// Decode the raw message to the match data.
return m, json.Unmarshal(raw, m.MatchData)
}
- 1 回答
- 0 关注
- 165 浏览
添加回答
举报
