pointers - 戈朗 : How to append pointer to slice to slice?

标签 pointers go slice dereference

我是一个 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.RepositoryRepository 似乎是两种不同的类型,一种来自包github,另一种来自当前包。同样,您也必须弄清楚这一点。

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

关于pointers - 戈朗 : How to append pointer to slice to slice?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42900701/

相关文章:

c 将字符串指针分配给其他字符串指针

go - 使用指向 channel 的指针

go - 类似于 Go 中的 .net 属性

html - Golang 在 Revel 中将字符串渲染为 html

arrays - 如何将 ruby​​ 中的数组切片为指定长度的子数组?

python - 如何自动将数据帧切片成批处理以避免 python 中的 MemoryError

vector - 为什么在使用置换器箱中的迭代器插入向量时得到 "expected u32, found &{integer}"?

c# - 获取指向自身内部结构的指针(不安全上下文)

c - printf 通过给定的指针和格式字符串。 float 问题

string - Go 中的不可变字符串