No short declarations at package level
August 18, 2023
A couple last points about short variable declarations before we move on…
Short variable declarations
…
Short variable declarations may appear only inside functions. In some contexts such as the initializers for “if”, “for”, or “switch” statements, they can be used to declare local temporary variables.
So first:
package foo
id := 1 // Invalid. Short declarations only possible within fucntions
var id = 1 // But this is valid.
Don’t ask me why this rule exists.
Second, the place where short variable declarations really shine deserves some examples: As initializes for if
, for
, and switch
statements. I’d personally be happy if this were the only place short declarations were allowed.
if err := DoAThing(); err != nil {
// the `err` variable exists only in this block.
// If another `err` variable existed outside this block, the local one shadows it.
}
for i, item := range items {
// i and item are unique to this block
}
switch result := GetResult() {
// the result variable is accessible in any of the case statements within the block
case "foo":
return result + "bar"
case "bar":
return "foo" + result
}
Quotes from The Go Programming Language Specification Version of August 2, 2023