Home  >  Article  >  Backend Development  >  Why do I get "declared but not used"?

Why do I get "declared but not used"?

王林
王林forward
2024-02-08 23:36:32727browse

Why do I get declared but not used?

php Editor Strawberry I encountered a common programming problem: Why do I encounter the "declared but not used" warning? In the process of writing code, we may define some variables or functions but end up not using them, which will trigger this warning. While this warning may seem harmless, it actually alerts us to a potential problem in our code. This article will explain why this warning appears and how to deal with it, let's find out together!

Question content

I am on a "go journey" and for one of the exercises, I wrote this function:

func Sqrt(x float64) float64 {
    z := 1.0
    var prev_z float64
    for (z - prev_z) != 0 {
        prev_z := z
        z -= (z*z - x) / (2*z)
        fmt.Println(z)
    }
    return z
}

Why does this give me "prev_z declared but not used"?

Solution

Because you declared a float64 type variable (prev_z) inside the for loop. After that, you use the := short declaration operator (line 5) again to initialize a new variable with the same name and type.

The following is the correct code:

func Sqrt(x float64) float64 {
z := 1.0
var prev_z float64
for (z - prev_z) != 0 {
    prev_z = z
    z -= (z*z - x) / (2*z)
    fmt.Println(z)
}
return z

}

The above is the detailed content of Why do I get "declared but not used"?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete