我是一个 Golang 新手,但我认为我已经掌握了指针和引用的要点,但显然不是:
我有一个必须返回 []github.Repository
的方法,这是来自 Github 客户端的类型。
API 调用返回分页结果,因此我必须循环直到没有更多结果,并将每次调用的结果添加到 allRepos
变量,然后返回 that。到目前为止,这是我所拥有的:
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)
最佳答案
嗯,这里有些地方不对:
您在评论中说“repos 的类型为 *[]github.Repository
”,但编译器的错误消息表明 repos 的类型为 []*Repository
“。编译器永远不会(除非有错误)出错。
请注意,*[]github.Repository
和 []*Repository
是完全不同的类型,尤其是第二种不是存储库和您不能(真的,没有 方式)在append()
期间取消引用这些指针:您有编写一个循环并取消引用每个 slice 项目并逐一追加。
奇怪的是:github.Repository
和Repository
似乎是两种不同的类型,一种来自包github,另一种来自当前包。同样,您也必须弄清楚这一点。
请注意,Go 中没有 引用。立即停止考虑这些:这是来自其他语言的概念,在 Go 中没有帮助(因为不存在)。
关于pointers - 戈朗 : How to append pointer to slice to slice?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42900701/