Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Golang complaining about unused variable inside for-loop

I have an unused variable inside a for-loop in golang.

I’m actually using it outside the for loop.

Goland keeps complaining about the unused variable.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How do I fix this?

var backoffSchedule = []time.Duration{
    1 * time.Second,
    3 * time.Second,
    10 * time.Second,
}
var response *http.Response

for _, backoff := range backoffSchedule {
    response, err := client.Do(request)
    if err == nil {
        break
    }
    fmt.Printf(os.Stderr, "Request error: %s", err)
    fmt.Printf(os.Stderr, "Retrying in %s", backoff)
    time.Sleep(backoff)

}

if err != nil {
    fmt.Printf("CRITICAL: API request failed: %s", err)
    os.Exit(2)
}

if response.StatusCode <= 199 || response.StatusCode >= 300 {
    // Non-successful response, alert
    fmt.Printf("CRITICAL: APIv request returned not ok: %s", response.Status)
    os.Exit(2)

Unused variable error

It’s also complaining about the unreferenced variable err. How do I make them available inside the function.

>Solution :

One way to make the error disappear would be to declare an err variable outside the loop:

var err error

That way, you can assign existing variables (rather than declare new variables) inside the loop

for _, backoff := range backoffSchedule {
    response, err = client.Do(request)
                 ^^^

Make sure this is what you want though, as response will be, outside the loop, the last value assigned in the loop.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading