Go has a common idiom that looks like this:
if val, err := func(); err != nil {
/* val and err are in scope */
...
}
/* val and err are no longer in scope */
using "short assignment". I'm certainly a fan. It feels similar to doing:
/* code not involving val */
{
int val;
if ((val = func()) == ERR_VALUE) {
/* Process the error */
}
/* Do something with val */
}
/* more code not involving val */
in C++. What trips me up is that, in the case where there is more than one variable in the first clause of the if, they have to have the same scope, i.e. you have to do either:
var err error
var val string
if val, err = func(); err != nil {
...
or
if val, err := func(); err != nil {
...
A very common use case would seem to be where you have a variable that you'd like to set in the first clause of the if, test for an error, and if there is none, continue with the rest of the program flow (and be able to use whatever values you assigned in executing the if). But, it seems to me, if you want to do that, you have to either:
-
Use a temporary variable, and then assign the persistent variable value inside an else:
var val if tempval, err := func(); err != nil { /* Process the error */ } else { val = tempval }
Declare the err variable with scope that extends past the if, as above.
The first option seems clunky - being forced to use an "else" clause just to make sure that the value doesn't fall out of scope - and the second throws away the advantages of limiting the scope of the variables. What idioms do more experienced Go programmers use for this (seemingly very common) situation?