doumi1912 2017-04-13 09:45
浏览 51


I have multiple types like this:

type QueryMessage struct {
    Header MessageHeader
    Type   MessageType
    Query  SqlQuery

type UpdateMessage struct {
    Header  MessageHeader
    Type    MessageType
    OldData map[string]interface{}
    NewData map[string]interface{}

type InsertMessage struct {
    Header MessageHeader
    Type   MessageType
    Data   map[string]interface{}

They all have two properties in common, Header and Type. In the end I need to aggregate them into an array of generic messages. At the moment my Message interface looks like this:

type Message interface {}

So what I basically do is something like this (casting them all to Message interface):

q := QueryMessage{ ... }
u := UpdateMessage{ ... }
i := InsertMessage{ ... }
allMessages := [3]Message { Message(q), Message(u), Message(i), }

This works, but it loses all the type information and I would like to be able to still expose Header and Type from the Message type (so that client code theoretically could cast the Message based on the Type back to it's original type.

How can this be done? I couldn't figure out a proper way, interfaces can't have properties and if I make Message a struct, Go doesn't allow me to cast e. g. a QueryMessage to a Message anymore.

  • 写回答

2条回答 默认 最新


      相关推荐 更多相似问题


      • ¥50 关于github项目下载运行
      • ¥15 苹果手机删除了qq软件,qq文件怎么恢复
      • ¥20 用mips 人力编程排序问题(能在mars按要求运行)
      • ¥15 Verilog小型神经网络(单层反馈神经网络)
      • ¥15 设计一个数字钟,实现时分秒的显示
      • ¥15 Clion使用头文件链接两个cpp
      • ¥15 51单片机无法触发外部中断问题
      • ¥15 基于半监督,无监督的调制识别
      • ¥15 cst求 阵列 rcs 时候 频域 时域求解器 应该怎样设置 才让两者 计算结果 相似 请附图
      • ¥15 关于#51单片机#的问题:大家帮我看一下为什么我的计时器数字一直不稳定