Fel*_*ida 2 pointers go slice dereference
我是 Golang 新手,但我认为我已经掌握了指针和引用的要点,但显然没有:
我有一个必须返回 a 的方法[]github.Repository,它是 go 中来自 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
}
Run Code Online (Sandbox Code Playgroud)
我的问题:如何附加每次调用的结果并返回类型的结果[]github.Repository?
另外,为什么取消引用在这里不起作用?我尝试替换allRepos = append(allRepos, repos...)为allRepos = append(allRepos, *(repos)...),但收到此错误消息:
Invalid indirect of (repos) (type []*github.Repository)
Run Code Online (Sandbox Code Playgroud)
嗯,这里有些不对劲:
您在评论中说“repos 的类型为*[]github.Repository”,但编译器的错误消息表明 repos 的类型为[]*Repository“。编译器永远不会(除非有错误)错误。
请注意,*[]github.Repository和[]*Repository是完全不同的类型,特别是第二个不是存储库的切片,并且您不能(实际上,没有办法 )在 期间取消引用这些指针append():您必须编写一个循环并取消引用每个切片项并逐一附加。
也很奇怪:github.Repository似乎Repository是两种不同的类型,一种来自 github 包,另一种来自当前包。再说一遍,你也必须搞清楚这一点。
请注意,Go 中没有引用。立即停止思考这些:这是来自其他语言的概念,在 Go 中没有帮助(因为不存在)。