doubutao6216 2018-10-31 13:59
浏览 3
已采纳

指针引用未存储在我的go程序的结构中

I am new to go-lang and I try to figure out how to work properly with structs and dependency injection. I am a bit stuck because I am not able to properly store a reference to another struct.

Here's my method that generates a CommandController. There is a valid reference to iris.Application.

func ProvideCommandController(application *iris.Application, commandRepository command.CommandRepository) (*interfaces.CommandController, error) {
commandController := interfaces.CommandController{}
commandController.Init(application, commandRepository)
commandController.Start()
return &commandController, nil

}

The struct looks like this:

type CommandController struct {
    commandRepository command.CommandRepository
    app   *iris.Application
}

func (c CommandController) Init(app *iris.Application, repository command.CommandRepository) {
    c.app = app
    c.commandRepository = repository
}

func (c CommandController) Start() {
    c.app.Get("/command", c.readAll)
    c.app.Get("/command/{id:string}/execute", c.executeCommand)

    c.app.Run(iris.Addr(":8080"))
}

When the ProvideCommandController function gets executed I can debug and observe that all references look good. Unfortunately, commandController.Start()fails because of c.app is nil.

What piece of understanding do I miss? Somehow, the stored reference get's deleted between the Init and the Start function call.

Thanks in advance :)

  • 写回答

1条回答 默认 最新

  • dongningwen1146 2018-10-31 14:03
    关注

    Change

    func (c CommandController) Init(app *iris.Application, repository command.CommandRepository)
    

    to

    func (c *CommandController) Init(app *iris.Application, repository command.CommandRepository)
    

    since Init receives c by value in your version, any changes it makes to c don't appear outside of the Init method.

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

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?