...and why the := operator is weird.

This *should* be a duplicate variable declaration error, if the it wasn't
for the := weirdness.

On Saturday, June 1, 2013 12:00:38 PM UTC+8, Jesse McNelis wrote:
On Sat, Jun 1, 2013 at 1:32 PM, <ri...@mcgeer.com <javascript:>> wrote:

I'm getting the "variable declared but not used" error in the following
function, and I can't see why:

func Sqrt(x float64) float64 {
var z float64 = 1.0
for i := 0; i < 10; i++ {
z := (z*z - x)/(2.0 * z)
return z

The error is in the line "z := (z*z - x)/(2.0 * z)". But z certainly is
used; it is returned immediately following the loop. The only way this
makes sense is if the z inside the loop is different from the z outside the
loop, but that would be very odd...
Not odd at all. You declared a new variable called 'z' inside the scope of
the loop.
Go lets you have variables of the same name in different scopes and ':='
declares and assigns
to a new variable.

This is one of the reasons this compile error is important to not ignore.

You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Search Discussions

Discussion Posts


Follow ups

Related Discussions

Discussion Navigation
viewthread | post
posts ‹ prev | 3 of 7 | next ›
Discussion Overview
groupgolang-nuts @
postedJun 1, '13 at 3:49a
activeJun 1, '13 at 3:53p



site design / logo © 2021 Grokbase