在另一个结构上访问函数

问题描述 投票:-3回答:1

将Go 1.11.x与echo框架一起使用。

我有以下结构和功能

type AccountController struct {
  ....
}

func (c *AccountController) ActiveAccountID() int {
  ....
  return 5
}

现在我想从另一个结构访问ActiveAccountID,这是我做的,

type TestController struct {
   Account *AccountController
}

func (c *TestController) AddData(ec echo.Context) error {
  ....
  id := c.Account.ActiveAccountID()     
  ....
}

但是当我打印/使用id var时,它只是给我一个内存指针错误?

我已经尝试过帐户控制器删除指针,但我仍然遇到内存指针问题。那么我做错了什么?

谢谢,

go
1个回答
1
投票

请注意结构的结构

type TestController struct {
   Account *AccountController
}

帐户是一个指针。它被启动到nil,所以如果你从来没有把它指向某个东西,那么它总是为零,当你试图像这样调用一个方法时,你会得到一个nil指针解除引用错误

// c *TestController
c.Account.ActiveAccountID()

如何/何时设置取决于您的使用案例。

另外,根据您的用例,您可以将其从指向嵌入式结构的指针更改

type TestController struct {
   Account AccountController
}

这样它总是在struct中,但如果你从其他地方分配它,它将被复制。根据您的使用情况,这可能是不可取的。

© www.soinside.com 2019 - 2024. All rights reserved.