douji2520 2018-10-14 05:27
浏览 167
已采纳

gob.Register名称未在另一个包中为接口注册

I have recently restructured my code so that now under the main package there are two packages: chain and api.

In chain I defined a few structs SomeStruct1, SomeStruct2 and an interface SomeInterface for those structs. The following is what chain/cli.go looks like.

package chain

type CLI struct{}

func (cli *CLI) Run() {
    ...
    gob.Register(SomeStruct1{})
    gob.Register(SomeStruct2{})
    ...
}

There is another similar api/api.go where inside Run() I put gob.Register(chain.SomeStruct1{}).

main.go looks like this:

package main

import (
    "myproj/api"
    "myproj/chain"
)

func main() {
    // I have also tried the following lines.
    // gob.Register(chain.SomeStruct1{})
    // gob.Register(chain.SomeStruct2{})
    go api.Run()

    cli := chain.CLI{}
    cli.Run()
}

However, I got the error gob: name not registered for interface: "main.SomeStruct1" at runtime. This did not happen when I had all the code inside one main package and I felt weird that SomeStruct1 is now under chain package but the error referred to main.SomeStruct1. Where did I get wrong of gob.Register()?

  • 写回答

1条回答 默认 最新

  • douzi9744 2018-10-16 07:45
    关注

    I have not been able to solve the problem completely and I think the cause was that chain.SomeStruct1 was somehow recognized at runtime as having the name main.SomeStruct1 while it was registered with the internal name main.SomeStruct1.

    Therefore a workaround I have now is using gob.RegisterName("main.SomeStruct1", chain.SomeStruct1).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler