Golang在for循环内部抱怨未使用的变量。

huangapple go评论85阅读模式
英文:

Golang complaining about unused variable inside for-loop

问题

我在golang的for循环中有一个未使用的变量。
实际上我在for循环外部使用它。
Goland一直抱怨这个未使用的变量。
我该如何解决这个问题?

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

它还抱怨未引用的变量err。我该如何在函数内部使它们可用?

英文:

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, &quot;Request error: %s&quot;, err)
	fmt.Printf(os.Stderr, &quot;Retrying in %s&quot;, backoff)
	time.Sleep(backoff)

}

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

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

Golang在for循环内部抱怨未使用的变量。

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

答案1

得分: 8

你有两个名为response的变量,一个在循环内部,另一个在循环外部。

下面是一个演示相同问题的示例代码:

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("在 if 作用域内:", someValue)
		}
	}

	fmt.Print("在 if 作用域外:", someValue)
}

问题在于你使用了:=,它默认会创建一个新的变量。

如果你在作用域外部声明err并使用=,你的代码就会正常工作。

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("在 if 作用域内:", someValue)
		}
	}

	fmt.Print("在 if 作用域外:", someValue)
}

另外需要注意的是,如果你在同一作用域中与已存在的变量同名,它的行为会有所不同。

package main

import (
	"fmt"
)

func foo() (int, error) {
	return 10, nil
}

func main() {
	someValue := 5

	fmt.Println("在调用 foo 之前:", someValue)

	someValue, err := foo()
	if err == nil {
		fmt.Print("在调用 foo 之后:", someValue)
	}
}

在这个例子中,我们同时给相同的someValue赋值,并使用:=声明了一个新的变量err

英文:

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 (
	&quot;fmt&quot;
)

func foo() (int, error) {
	return 10, nil
}

func main() {
	someValue := 5
	
	if (someValue == 5) {
		someValue, err := foo()
		if (err == nil) {
			fmt.Println(&quot;Inside if scope:&quot;, someValue)
		}
	}
	
	fmt.Print(&quot;Outside if scope:&quot;, 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 (
	&quot;fmt&quot;
)

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(&quot;Inside if scope:&quot;, someValue)
		}
	}
	
	fmt.Print(&quot;Outside if scope:&quot;, 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 (
	&quot;fmt&quot;
)

func foo() (int, error) {
	return 10, nil
}

func main() {
	someValue := 5
	
	fmt.Println(&quot;Before foo:&quot;, someValue)
	
	someValue, err := foo()
	if (err == nil) {
		fmt.Print(&quot;After foo:&quot;, someValue)
	}
}

Here we are assigning to the same someValue and declaring a new variable err at the same time with :=.

答案2

得分: 2

为了消除错误,一种方法是在循环外部声明一个err变量:

var err error

这样,你可以在循环内部对已存在的变量进行赋值(而不是声明新的变量):

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

请确保这是你想要的,因为在循环外部,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.

答案3

得分: 0

为了进行错误检测,也许你可以对response变量添加一个空值检查。这可能是一个解决方案。例如:

if response == nil {
    break
}

请分享你对这种情况的首选或发现的答案。

英文:

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.

huangapple
  • 本文由 发表于 2021年11月8日 15:42:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/69880031.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定