簡體   English   中英

如何正確使用嵌套的 for 循環來遍歷 golang 中的行?

[英]How do I properly use nested for loop to range over rows in golang?

我正在嘗試迭代嵌套循環,如下所示,但在第一個循環中聲明的變量,如varOne, varTwo, varThree沒有進入第二個循環

事實上,在for rowTwo:= range rowsTwo {

誰能指出我做錯了什么或如何

func StudentScore() {

    var appendedScores []interface{}

    for rowOne := range rowsOne {
        varOne := rowOne.FirstName
        varTwo := rowOne.LastName
        varThree := rowOne.UserName

        req, _ := http.NewRequest("GET", fmt.Sprintf("https://example.com/users/%s/score", varThree), nil)
    
        client := &http.Client{}
        resp, _ := client.Do(req)


        type responseData struct {
            FirstName   string `json:"first_name"`
            LastName     string  `json:"last_name"`
            Score       float64 `json:"score"`

        }

        type StudentData struct {
            UserName   string `json:"username_name"`
            Score      float64 `json:"score"`
        }

        var rowsTwo []responseData
        
        respBody, _ := ioutil.ReadAll(resp.Body)
        err = json.Unmarshal(respBody, &rowsTwo) 
        fmt.Println("response: ", rowsTwo)
        
//         var appendedScores []interface{}
        studentData := &StudentData{}

        for rowTwo := range rowsTwo {

            fmt.Println("print vars from first loop: ", varOne, varTwo, varThree)
            fmt.Println("api response: ", resp)

            studentData.UserName=string(varThree)
            studentData.Score=float64(rowTwo.Score)

            appendedScores = append(appendedScores, *studentData)
        }

    }
    fmt.Println("student scores: ", appendedScores)

}

我要做的幾乎是使用第一行范圍內的行中的值並用於生成要在第二個 for 循環中使用的新值,以便我可以打印最終值。 所以 2 個嵌套 for 循環的唯一原因是因為我需要來自第一個 for 循環的值

有什么遺漏或更好的方法嗎?

type StudentScore struct {
    UserName string  `json:"user_name"`
    Score    float64 `json:"score"`
}

func GetStudentScore() ([]StudentScore, error) {
    var scores []StudentScore

    for _, row := range rowsOne {
        s := StudentScore{UserName: row.UserName}

        // request score data
        resp, err := http.Get(fmt.Sprintf("https://example.com/users/%s/score", s.UserName))
        if err != nil {
            return nil, err
        }
        defer resp.Body.Close()

        // unmarshal score data
        var data struct {
            Score float64 `json:"score"`
        }
        if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
            return nil, err
        }

        // set score field on Student instance
        s.Score = data.Score

        // append StudentScore
        scores = append(scores, s)
    }

    return scores, nil
}

要同時執行此操作,您可以執行以下操作:

type StudentScore struct {
    UserName string  `json:"user_name"`
    Score    float64 `json:"score"`
}

func GetStudentScore() ([]StudentScore, error) {
    var wg sync.WaitGroup
    var ch = make(chan StudentScore)

    for _, row := range rowsOne {
        wg.Add(1)

        // for each row execute the retrieveStudentScore in a separate goroutine
        go func() {
            if err := retrieveStudentScore(row.UserName, ch); err != nil {
                log.Println("failed to retrieve StudentScore:", err)
            }
            wg.Done()
        }()
    }
    
    go func() {
        wg.Wait() // wait until every retrieveStudentScore is finished
        close(ch) // this will cause the range loop below to exit
    }()

    var scores []StudentScore
    for s := range ch {
        // append StudentScore received from channel
        scores = append(scores, s)
    }

    return scores, nil
}
func retrieveStudentScore(userName string, ch chan StudentScore) error {
    // request score data
    resp, err := http.Get(fmt.Sprintf("https://example.com/users/%s/score", userName))
    if err != nil {
        return err
    }
    defer resp.Body.Close()

    // unmarshal score data
    var data struct {
        Score float64 `json:"score"`
    }
    if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
        return err
    }
    
    // send StudentScore to channel
    ch <- StudentScore{UserName: userName, Score: data.Score}
    
    return nil
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM