diff --git a/doc/effective_go.html b/doc/effective_go.html index e825f747abf..0e0a36bd526 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) +
+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:
+
v
+(if v
is already declared in an outer scope, the declaration will create a new variable),v
, and
+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.
+
diff --git a/doc/effective_go.tmpl b/doc/effective_go.tmpl index 8ca4902c3b4..21b3b22df67 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) +
+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:
+
v
+(if v
is already declared in an outer scope, the declaration will create a new variable),v
, and
+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.
+