[英]Golang: How to append pointer to slice to slice?
我是一个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)...)
替换allRepos = append(allRepos, repos...)
allRepos = append(allRepos, *(repos)...)
但是我收到此错误消息:
Invalid indirect of (repos) (type []*github.Repository)
嗯,这里有些不对劲:
你在评论中说“repos是*[]github.Repository
类型”,但是编译器的错误消息表明repos的类型为[]*Repository
“。编译器永远不会(除了bug)时出错。
注意*[]github.Repository
和[]*Repository
是完全不同的类型,特别是第二个不是一个存储库片段,你不能 (真的, 没有 办法 )在append()
期间取消引用这些指针:你必须写循环并取消引用每个切片项并逐个追加。
奇怪的是: github.Repository
和Repository
似乎是两个不同的类型,来自包github,另一个来自当前包。 同样,你也必须顺利完成。
请注意,Go中没有引用。 不要再考虑这些了:这是一个来自其他语言的概念,在Go中没有帮助(因为不存在)。
在您的示例中,解除引用不正确。 你应该这样做:
allRepos = append(allRepos, *repos...)
这是一个简单的示例,用于解引用指向字符串切片的指针。 https://play.golang.org/p/UDzaG5z8Pf
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.