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

时间:2018-10-31 13:59:40

标签: go

我是go-lang的新手,我试图弄清楚如何正确使用结构和依赖项注入。我有点卡住了,因为我无法正确存储对另一个结构的引用。

这是我的生成CommandController的方法。有效引用了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

}

结构如下:

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"))
}

执行ProvideCommandController函数时,我可以调试并观察所有引用看起来不错。不幸的是,commandController.Start()由于c.app为零而失败。

我想念什么?不知何故,在Init和Start函数调用之间会删除存储的引用。

预先感谢:)

1 个答案:

答案 0 :(得分:2)

更改

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

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

由于Init在您的版本中通过值接收了c,因此对c所做的任何更改都不会出现在Init方法之外。