How can I redeclare a variable from a different block in a short variable declaration?
func f() (err os.Error) {
proc, err := os.StartProcess(blah blah blah)
// the new err masks the return value?
}
There's a long thread about this, and an issue, but I'm interested in how to work around this for the time being.
The Go specification for short variable declarations is clear:
Therefore, in a short variable declaration, you can't redeclare variables originally declared in a different block.
Here's an example of how to get around this restriction by declaring a local variable (
e
) in the inner block and assigning it (e
) to a variable (err2
) declared in an outer block.Output:
Here's the previous example rewritten to use explicit regular variable declarations and named function parameters rather than implicit short variable declarations. Variable declarations can always be written explicitly as regular variable declarations or named function parameters; implicit short variable declarations are merely a shorthand for regular variable declarations.
Output:
In your example, the short variable declaration of
err
redeclares the return parameter declaration oferr
; they are in the same block. Therefore, the newerr
does not mask the return parametererr
.There is no way to bypass the scope rules of a
:=
declaration. Just be explicit usingvar
and=
.