From: Rob Pike Date: Tue, 20 Dec 2011 22:15:35 +0000 (-0800) Subject: effective_go: redeclaration X-Git-Tag: weekly.2011-12-22~84 X-Git-Url: http://www.git.cypherpunks.su/?a=commitdiff_plain;h=a41006f35a5931387a3111739e4c97ff3568bbcc;p=gostls13.git effective_go: redeclaration Fixes #2455. Fixes #2013. R=rsc, r, gri CC=golang-dev https://golang.org/cl/5498053 --- diff --git a/doc/effective_go.html b/doc/effective_go.html index e825f747ab..0e0a36bd52 100644 --- a/doc/effective_go.html +++ b/doc/effective_go.html @@ -531,12 +531,62 @@ if err != nil { } d, err := f.Stat() if err != nil { + f.Close() return err } codeUsing(f, d) +

Redeclaration

+ +

+An aside: The last example in the previous section demonstrates a detail of how the +:= short declaration form works. +The declaration that calls os.Open reads, +

+ +
+f, err := os.Open(name)
+
+ +

+This statement declares two variables, f and err. +A few lines later, the call to f.Stat reads, +

+ +
+d, err := f.Stat()
+
+ +

+which looks as if it declares d and err. +Notice, though, that err appears in both statements. +This duplication is legal: err is declared by the first statement, +but only re-assigned in the second. +This means that the call to f.Stat uses the existing +err variable declared above, and just gives it a new value. +

+ +

+In a := declaration a variable v may appear even +if it has already been declared, provided: +

+ + + +

+This unusual property is pure pragmatism, +making it easy to use a single err value, for example, +in a long if-else chain. +You'll see it used often. +

+

For

diff --git a/doc/effective_go.tmpl b/doc/effective_go.tmpl index 8ca4902c3b..21b3b22df6 100644 --- a/doc/effective_go.tmpl +++ b/doc/effective_go.tmpl @@ -527,12 +527,62 @@ if err != nil { } d, err := f.Stat() if err != nil { + f.Close() return err } codeUsing(f, d) +

Redeclaration

+ +

+An aside: The last example in the previous section demonstrates a detail of how the +:= short declaration form works. +The declaration that calls os.Open reads, +

+ +
+f, err := os.Open(name)
+
+ +

+This statement declares two variables, f and err. +A few lines later, the call to f.Stat reads, +

+ +
+d, err := f.Stat()
+
+ +

+which looks as if it declares d and err. +Notice, though, that err appears in both statements. +This duplication is legal: err is declared by the first statement, +but only re-assigned in the second. +This means that the call to f.Stat uses the existing +err variable declared above, and just gives it a new value. +

+ +

+In a := declaration a variable v may appear even +if it has already been declared, provided: +

+ + + +

+This unusual property is pure pragmatism, +making it easy to use a single err value, for example, +in a long if-else chain. +You'll see it used often. +

+

For