Description
Operator ^
lifts the declaration of a variable to the enclosing scope when used in if and for statements:
if ^f, err := os.Open("foo.bar"); err != nil {
return fmt.Errorf("error opening file: %w", err)
}
f.Read() // ok: f is in scope now
Using ^f
, the declaration of f escapes the if statement while keeping err local to the if statement.
The expression ^f, err :=
works just like f, err :=
except that if f is declared, it is declared in the enclosing block.
Other notes:
-
^ can only be used with if and for; anywhere else it is illegal
To be more exact:
- in the ShortVarDecl of the SimpleStatement of the IfStmt
- in the InitStmt of the ForClause of the ForStmt
- in the RangeClause of the ForStmt -
Single lifts are allowed only; ^^f is illegal, etc.
-
I know that ^ is used as bitwise XOR operator; this should be no problem as for example * is also used for both derefencing and multiplication operator
-
I chose ^ because it is a visual cue for the effect of the operation.