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:
a short variable declaration may
redeclare variables provided they were
originally declared in the same block
with the same type, and at least one
of the non-blank variables is new.
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.
package main
import (
"fmt"
"os"
)
func f() (err1 os.Error, err2 os.Error) {
fi, err1 := os.Stat("== err1 os.Error ==")
_ = fi
{
fi, e := os.Stat("== e os.Error ==")
_ = fi
err2 = e
}
return
}
func main() {
err1, err2 := f()
fmt.Println("f() err1:", err1)
fmt.Println("f() err2:", err2)
}
Output:
f() err1: stat == err1 os.Error ==: no such file or directory
f() err2: stat == e os.Error ==: no such file or directory
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.
package main
import (
"fmt"
"os"
)
func f() (err1 os.Error, err2 os.Error) {
var fi *os.FileInfo
fi, err1 = os.Stat("== err1 os.Error ==")
_ = fi
{
var fi *os.FileInfo
fi, err2 = os.Stat("== err2 os.Error ==")
_ = fi
}
return
}
func main() {
err1, err2 := f()
fmt.Println("f() err1:", err1)
fmt.Println("f() err2:", err2)
}
Output:
f() err1: stat == err1 os.Error ==: no such file or directory
f() err2: stat == err2 os.Error ==: no such file or directory
In your example, the short variable declaration of err
redeclares the return parameter declaration of err
; they are in the same block. Therefore, the new err
does not mask the return parameter err
.
There is no way to bypass the scope rules of a :=
declaration. Just be explicit using var
and =
.