Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"declared and not used" Error

Tags:

go

I get this error saying that I'm not using a variable… but to my noob eyes, it looks like I am:

func Sqrt(x float64) float64 {

    z := float64(x);

    for i := 0; i < 10; i++ {
        z := z - (z*z - x) / (2 * z);
    }

    return z;
}

Can anyone point out what I'm missing about the language? I think it has to do with = vs. := and scoping, but I'm not sure.

like image 731
dubeegee Avatar asked Aug 14 '13 20:08

dubeegee


People also ask

How do you avoid declared but not used?

To avoid this error – Use a blank identifier (_) before the package name os. In the above code, two variables name and age are declared but age was not used, Thus, the following error will return. To avoid this error – Assign the variable to a blank identifier (_).

What happens if you use a variable that has not been declared?

The identifier is undeclared: In any programming language, all variables have to be declared before they are used. If you try to use the name of a such that hasn't been declared yet, an “undeclared identifier” compile-error will occur.

What is the difference between and := IN go?

The subtle difference between = and := is when = used in variable declarations. the above declaration creates a variable of a particular type, attaches a name to it, and sets its initial value. Either the type or the = expression can be omitted, but not both. Besides, := may appear only inside functions.

When there are many variables declared but haven't been used then it is called as?

First, a minor point: declaring a variable that's never used is a waste of memory, and thus is itself a bug.


2 Answers

The := in your for-loop declares a new variable z which shadows the outer z. Turn it into a plain = to fix the problem.

func Sqrt(x float64) float64 {

    z := x

    for i := 0; i < 10; i++ {
        z = z - (z*z - x) / (2 * z);
    }

    return z;
}

By the way, for equal precision and a bit more speed you could try the following implementation which does two of your steps at once:

func Sqrt(x float64) float64 {
    z := x
    for i := 0; i < 5; i++ {
        a := z + x/z
        z = a/4 + x/a
    }
    return z
 }
like image 184
fuz Avatar answered Oct 12 '22 06:10

fuz


Here is another way to look at the function

func Sqrt(x float64) (z float64) {
    z = x
    for i := 0; i < 10; i++ {
        z = z - (z*z - x)/(2*z);
    }
    return
}
like image 33
Baba Avatar answered Oct 12 '22 07:10

Baba