dongqiuwei8667 2017-03-07 08:46
浏览 67
已采纳

调用struct方法

This code works fine:

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

But this code gives me error:

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

controllers\feed_controller.go:35: cannot call pointer method on postgres.FeedService literal controllers\feed_controller.go:35: cannot take the address of postgres.FeedService literal

Why this two pieces of code is not equal ?

Here is a struct declaration:

type FeedService struct {

}

func (s *FeedService) GetAllRssFeeds() ([]*quzx.RssFeed, error) {
  • 写回答

1条回答 默认 最新

  • dqc42632 2017-03-07 08:51
    关注

    Your FeedService.GetAllRssFeeds() method has pointer receiver, so a pointer to FeedService is needed to call this method.

    In your first example you use a short variable declaration to store a FeedService struct value in a local variable. Local variables are addressable, so when you write feedService.GetAllRssFeeds() after that, the compiler will automatically take the address of feedService and use that as the receiver value. It is a shorthand for:

    feeds, err := (&feedService).GetAllRssFeeds()
    

    It is in Spec: Calls:

    If x is addressable and &x's method set contains m, x.m() is shorthand for (&x).m().

    In your second example you don't create a local variable, you just use a struct composite literal, but by itself it is not (automatically) addressable, so the compiler cannot obtain a pointer to FeedService value to be used as the receiver, and hence cannot call the method.

    Note that it is allowed to take the address of a composite literal explicitly, so the following also works:

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

    This is in Spec: Composite literals:

    Taking the address of a composite literal generates a pointer to a unique variable initialized with the literal's value.

    See related questions:

    What is the method set of `sync.WaitGroup`?

    Calling a method with a pointer receiver by an object instead of a pointer to it?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 Windows Server 2016利用兩張網卡處理兩個不同網絡
  • ¥15 Python中knn问题
  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源