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.
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)
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.