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.
CodePudding user response:
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.
CodePudding user response:
You have two variables named response
, one inside the loop and another outside the loop.
Here is an example that demonstrates the same issue.
package main
import (
"fmt"
)
func foo() (int, error) {
return 10, nil
}
func main() {
someValue := 5
if (someValue == 5) {
someValue, err := foo()
if (err == nil) {
fmt.Println("Inside if scope:", someValue)
}
}
fmt.Print("Outside if scope:", someValue)
}
The issue here is that you are using :=
, which by default creates a new variable.
If you declare err
outside of the scope and use =
your code will work.
package main
import (
"fmt"
)
func foo() (int, error) {
return 10, nil
}
func main() {
someValue := 5
var err error
if (someValue == 5) {
someValue, err = foo()
if (err == nil) {
fmt.Println("Inside if scope:", someValue)
}
}
fmt.Print("Outside if scope:", someValue)
}
Another note to how go behaves is that if you are in the same scope as an already existing variable, it works differently.
package main
import (
"fmt"
)
func foo() (int, error) {
return 10, nil
}
func main() {
someValue := 5
fmt.Println("Before foo:", someValue)
someValue, err := foo()
if (err == nil) {
fmt.Print("After foo:", someValue)
}
}
Here we are assigning to the same someValue
and declaring a new variable err
at the same time with :=
.
CodePudding user response:
For the sake of error detection, maybe you can add a nil check for the response
variable as well. This might be a solution for you. For eq.
if response== nil {
break
}
Please share your preferred or discovered answer to the situation.