为了账号安全,请及时绑定邮箱和手机立即绑定

使用 Go 递归在数组中累积/追加值时出现问题

使用 Go 递归在数组中累积/追加值时出现问题

Go
HUWWW 2023-05-08 17:57:09
首先,这是我第一个使用 Go 的非虚拟程序。任何建议将不胜感激。代码说明:我想从对信息进行分页的 API 中检索所有信息。所以我想遍历所有页面以获取所有信息。这是我到目前为止所做的:我有这两个功能:func request(requestData *RequestData) []*ProjectsResponse {    client := &http.Client{        Timeout: time.Second * 10,    }    projects := []*ProjectsResponse{}    innerRequest(client, requestData.URL, projects)    return projects}func innerRequest(client *http.Client, URL string, projects []*ProjectsResponse) {    if URL == "" {        return    }    req, err := http.NewRequest("GET", URL, nil)    if err != nil {        log.Printf("Request creation failed with error %s\n", err)    }    req.Header.Add("Private-Token", os.Getenv("API_KEY"))    res, err := client.Do(req)    log.Printf("Executing request: %s", req.URL)    if err != nil {        log.Printf("The HTTP request failed with error %s\n", err)    }    data, _ := ioutil.ReadAll(res.Body)    var response ProjectsResponse    err = json.Unmarshal(data, &response)    if err != nil {        log.Printf("Unmarshalling failed with error %s\n", err)    }    projects = append(projects, &response)    pagingData := getPageInformation(res)    innerRequest(client, pagingData.NextLink, projects)}不良行为:数组中的值projects []*ProjectsResponse被附加到递归的每次迭代中,但是当递归结束时,我得到一个空数组列表。因此,不知何故,在innerRequests结束之后,在方法project内的变量中request我什么也得不到。希望有人发现我的错误。提前致谢。
查看完整描述

2 回答

?
皈依舞

TA贡献1851条经验 获得超3个赞

我猜你所有的项目对象都在函数范围内,所以当函数结束时它们不再存在。我认为在调用 innerRequest 之前您不需要项目存在,因此您应该只让该方法返回项目。我认为这样的事情应该有效......


func innerRequest(client *http.Client, URL string) []*ProjectsResponse {


if URL == "" {

    return nil

}


//More code...


pagingData := getPageInformation(res)

return append([]*ProjectsResponse{&response}, innerRequest(client, pagingData.NextLink)...)

}


查看完整回答
反对 回复 2023-05-08
?
慕容3067478

TA贡献1773条经验 获得超3个赞

混淆在于sliceGo 中处理 a 的方式。这是深入的解释,但我会缩写。

常见的误解是slice你传递的是对的引用slice,这是错误的。处理切片时操作的实际变量称为切片标头。这是一个简单的底层数组struct引用,并遵循 Go 的按值传递规则,即它在传递函数时被复制。因此,如果未返回,您将不会拥有更新的标头。

从递归返回数据遵循一个简单的模式。这是一个基本示例。我还包括一个不需要返回的版本,但作为参考对切片进行操作,这将修改原始版本。(注意:传递切片指针通常不被认为是惯用的 Go)

游乐场链接:https://play.golang.org/p/v5XeYpH1VlF

// correct way to return from recursion

func addReturn(s []int) []int {

    if finalCondition(s) {

        return s

    }

    s = append(s, 1)

    return addReturn(s)

}


// using a reference

func addReference(s *[]int) {

    if finalCondition(*s) {

        return

    }

    *s = append(*s, 1)

    addReference(s)

}


// whatever terminates the recursion

func finalCondition(s []int) bool {

    if len(s) >= 10 {

        return true

    }

    return false

}


查看完整回答
反对 回复 2023-05-08
  • 2 回答
  • 0 关注
  • 118 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信