dongxun8189 2015-01-12 22:32
浏览 32

En / Decode结构包含许多接口,这些接口具有不同的实现,每个接口都带有gob

I have a quite complex struct that contains many interfaces with each different implementations. For en/decoding that struct in gob I seem to have to register every implementation that could be possibly used for every interface. So I end up with a method along these lines:

func registerImplementations() {
    gob.Register(&Type1{})
    gob.Register(&Type2{})
    gob.Register(&Type3{})
    gob.Register(&Type4{})
    ....

}

which I need to call before en/decoding. Is there an easier way to do this? Or should I look into possibilities for generating this method, since it's quite tedious to keep track of all possible implementations?

  • 写回答

1条回答 默认 最新

  • du3669 2015-01-13 08:59
    关注

    The documentation says:

    We must register the concrete type for the encoder and decoder (which would
    normally be on a separate machine from the encoder). On each end, this tells the
    engine which concrete type is being sent that implements the interface.
    

    So, at some point, you're going to want to call gob.Register, but you do want your code to be maintainable. This leaves (broadly) two options:

    • Creating a function like you're doing now, calling each struct after one another.
      • Advantage: all your Register-calls in a list, so you'll easily spot if you miss one, and you surely won't register one twice.
      • Disadvantage: you'll have to update it when using another implementation. You'll also have to call this function some time before encoding/decoding.
    • Creating something like this:

      func Register(i interface{}) error {
          gob.Register(i)
          return nil
      }
      

      And then when writing a new implementation in your (let's say) dummy package, you can put this line below / above the interface declaration.

      var regResult = reg.Register(myNewInterface{})
      

    This will be called on startup (because it's global).

    • Advantage: not having to update the registerImplementations method.
    • Disadvantage: you'll have your registers all across your code (which can consist of a lot of files) - so you might miss one.

    As to which is better: I'll leave that up to you.

    评论

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用