Why do I get 'declared but not used'?

王林
Release: 2024-02-08 23:36:32
forward
706 people have browsed it

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
}
Copy after login

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
Copy after login

}

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!