Using Go 1.11.x with the echo framework.
I have the following struct and function
type AccountController struct {
....
}
func (c *AccountController) ActiveAccountID() int {
....
return 5
}
Now I want to access the ActiveAccountID
from another struct, this is how i did it,
type TestController struct {
Account *AccountController
}
func (c *TestController) AddData(ec echo.Context) error {
....
id := c.Account.ActiveAccountID()
....
}
But when I print / use the id var, it just gives me a memory pointer error?
I have tried the account controller to remove the pointer but i still got the memory pointer issue. So what am I doing wrong?
Thanks,
答案 0 :(得分:1)
注意结构的结构
type TestController struct {
Account *AccountController
}
帐户是一个指针。它已初始化为nil
,因此,如果您从未将其设置为指向某个东西,它将始终为nil,并且当您尝试像这样对它调用方法时,将收到nil指针解除引用错误
// c *TestController
c.Account.ActiveAccountID()
设置方式/时间取决于您的用例。
还可以根据您的用例将其从指针更改为嵌入式结构
type TestController struct {
Account AccountController
}
这样,它始终位于结构内部,但是如果您从其他位置进行分配,它将被复制。根据您的用例,这可能是不希望的。