【发布时间】: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)
【问题讨论】:
-
解除引用应该有效。也许变量
repos有另一种类型。工作示例:play.golang.org/p/UDzaG5z8Pf
标签: pointers go slice dereference