duanbangzhou7809 2017-05-24 18:55
浏览 25
已采纳

类型断言恐慌

I would like to apply Dependency injection on my code so I create every part of it as a service.

type BaseService struct {
    Config config.Container
    SQL    *gorm.DB
    Mongo  *mgo.Session
    Logger logger.Logger
}

type BaseInterface interface {
    Set(c config.Container, sq *gorm.DB, m *mgo.Session, l logger.Logger) BaseInterface
}

func (s BaseService) Set(c config.Container, sq *gorm.DB, m *mgo.Session, l logger.Logger) BaseInterface {
    s.Config = c
    s.SQL = sq
    s.Mongo = m
    s.Logger = l
    return s
}

func NewSetupService(c config.Container, s *gorm.DB, m *mgo.Session, l logger.Logger) SetupService {
    return SetupService{}.Set(c, s, m, l).(SetupService)
}
...
...

There is the BaseService and every service extend it as the follow:

type SetupService struct {
    BaseService
}

type SetupInterface interface {
    Do()
}

func (s SetupService) Do() {
    mongo := s.Mongo.Clone()
    defer mongo.Close()
    mongoDB := mongo.DB(s.Config.Database.Mongo.DB)
...
...

But when I call the NewSetupService function I got a panic which is not clear for me. Basically I create a SetupService{} and call the Set function of this struct, am I right? Then why I got this panic:

panic: interface conversion: api.BaseInterface is api.BaseService, not api.SetupService [recovered]
    panic: interface conversion: api.BaseInterface is api.BaseService, not api.SetupService
  • 写回答

1条回答 默认 最新

  • duancan65665 2017-05-24 19:01
    关注

    When you return a BaseInterface from a function, the type of the reference is actually BaseInterface and not SetupService. It is true that SetupService does satisfy BaseInterface, but that type information is lost when you cast.

    What you could do is this:

    func (s SetupService) Set() SetupService {
      s.BaseService.Set()
      return s
    }
    

    One thing to note though is that you're not using pointers, so each method call copies the object and state mutations are not preserved. You might want to replace these:

    func (s SetupService) ...
    

    With these:

    func (s *SetupService) ...
    

    Update: Why not just avoid returning the result of Set here?

    s := SetupService{}
    s.Set(...)
    return s
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求帮我调试一下freefem代码
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图