Golang:如何将指针附加到切片到切片?

Golang: How to append pointer to slice to slice?

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

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

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

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

}

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

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

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

嗯,这里有点不对:

你在评论中说 "repos is of type *[]github.Repository" 但编译器的错误消息表明 repos 是 []*Repository 类型。编译器永远不会(除非有错误)错误。

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

也很奇怪:github.RepositoryRepository好像是两种不同的类型,一种来自包github,另一种来自当前包。同样,您也必须弄清楚这一点。

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

在您的示例中,解除引用不正确。你应该这样做:

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

这里是一个简单的示例,其中取消引用了指向一段字符串的指针。 https://play.golang.org/p/UDzaG5z8Pf