【问题标题】:Golang: How to append pointer to slice to slice?Golang:如何将指向切片的指针附加到切片?
【发布时间】:2017-08-11 13:26:23
【问题描述】:

我是 Golang 新手,但我认为我已经掌握了指针和引用的基本要素,但显然不是:

我有一个方法必须返回一个[]github.Repository,这是来自Github客户端的一个类型。

API 调用返回分页的结果,因此我必须循环直到没有更多结果,并将每次调用的结果添加到allRepos 变量,然后返回那个。这是我目前所拥有的:

func (s *inmemService) GetWatchedRepos(ctx context.Context, username string) ([]github.Repository, error) {
    s.mtx.RLock()
    defer s.mtx.RUnlock()

    opt := &github.ListOptions{PerPage: 20}

    var allRepos []github.Repository

    for {
        // repos is of type *[]github.Repository
        repos, resp, err := s.ghClient.Activity.ListWatched(ctx, "", opt)

        if err != nil {
            return []github.Repository{}, err
        }

        // ERROR: Cannot use repos (type []*github.Repository) as type github.Repository
        // but dereferencing it doesn't work, either
        allRepos = append(allRepos, repos...)
        if resp.NextPage == 0 {
            break
        }
        opt.Page = resp.NextPage
    }

    return allRepos, nil

}

我的问题:如何附加每个调用的结果并返回[]github.Repository 类型的结果?

另外,为什么取消引用在这里不起作用?我尝试将allRepos = append(allRepos, repos...) 替换为allRepos = append(allRepos, *(repos)...),但收到以下错误消息:

Invalid indirect of (repos) (type []*github.Repository)

【问题讨论】:

标签: pointers go slice dereference


【解决方案1】:

嗯,这里有些不对劲:

您在评论中说“repos 的类型为 *[]github.Repository”,但编译器的错误消息表明 repos 的类型为 []*Repository”。编译器永远不会出错(除非有错误)。

请注意*[]github.Repository[]*Repository 是完全不同的类型,尤其是第二个不是 Repositories 的一部分而你不能(真的,有no way) 在append() 期间取消引用这些指针:您必须编写一个循环并取消引用每个切片项并逐个追加。

还有什么奇怪的:github.RepositoryRepository 似乎是两种不同的类型,一种来自包 github,另一种来自当前包。同样,您也必须弄清楚这一点。

请注意,Go 中 没有 引用。立即停止考虑这些:这是来自其他语言的概念,在 Go 中没有帮助(因为不存在)。

【讨论】:

  • 我打错了错误信息。有一个 Repository 类型,它存在于包 github 中。所以我想做的方法是取消引用变量repos中的每个存储库,然后将每个存储库附加到allRepos?
  • 是的,当然。对于[]int,您只能附加int 而不能附加*int。作为语法糖,您可以将[]int 附加到[]int,如append(orig, fresh...),但您不能将[]**[]***int 附加到[]int,只是因为“深处隐藏着一些整数”。
【解决方案2】:

在您的示例中,取消引用不正确。你应该这样:

allRepos = append(allRepos, *repos...)

这里有一个简单的例子,它取消了指向字符串切片的指针。 https://play.golang.org/p/UDzaG5z8Pf

【讨论】:

  • 仍然不起作用...用allRepos = append(allRepos, *repos...) 替换该行会给我同样的错误消息(invalid indirect of repos (type []*github.Repository)
猜你喜欢
  • 1970-01-01
  • 2016-12-28
  • 2015-05-01
  • 2021-09-15
  • 2015-10-16
  • 1970-01-01
  • 2019-07-18
  • 2015-02-21
相关资源
最近更新 更多