调用结构体的方法

2023-12-19

这段代码工作正常:

feedService := postgres.FeedService{}
feeds, err := feedService.GetAllRssFeeds()

但这段代码给了我错误:

feeds, err = postgres.FeedService{}.GetAllRssFeeds()

controllers\feed_controller.go:35: 无法调用指针方法 postgres.FeedService 文字控制器\feed_controller.go:35: 不能 获取 postgres.FeedService 文字的地址

为什么这两段代码不相等?

这是一个结构声明:

type FeedService struct {

}

func (s *FeedService) GetAllRssFeeds() ([]*quzx.RssFeed, error) {

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

调用结构体的方法 的相关文章