Your FeedService.GetAllRssFeeds()
方法有指针接收器,因此指向FeedService
需要调用该方法。
在您的第一个示例中,您使用短变量声明 https://golang.org/ref/spec#Short_variable_declarations存储一个FeedService
局部变量中的结构体值。局部变量是可寻址的 https://golang.org/ref/spec#Address_operators,所以当你写feedService.GetAllRssFeeds()
之后编译器会自动获取地址feedService
并将其用作接收者值。它是以下内容的简写:
feeds, err := (&feedService).GetAllRssFeeds()
它是在规格: 电话: https://golang.org/ref/spec#Calls
If x
是可寻址的并且&x
的方法集包含m
, x.m()
是简写(&x).m()
.
在第二个示例中,您不创建局部变量,仅使用结构复合文字 https://golang.org/ref/spec#Composite_literals,但它本身不能(自动)寻址,因此编译器无法获取指向的指针FeedService
值用作接收者,因此无法调用该方法。
请注意,允许获取复合文字的地址明确地,所以以下也有效:
feeds, err := (&postgres.FeedService{}).GetAllRssFeeds()
这是在规格:复合文字: https://golang.org/ref/spec#Composite_literals
获取地址 https://golang.org/ref/spec#Address_operators复合文字生成一个指向唯一的指针variable https://golang.org/ref/spec#Variables使用文字值初始化。
查看相关问题:
`sync.WaitGroup`的方法集是什么? https://stackoverflow.com/questions/42477951/what-is-the-method-set-of-sync-waitgroup/42480671#42480671
通过对象而不是指向它的指针来调用带有指针接收器的方法? https://stackoverflow.com/questions/38481420/calling-a-method-with-a-pointer-receiver-by-an-object-instead-of-a-pointer-to-it/38481697#38481697