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 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP