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


Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Related Content


Short variable declarations, cont'd

Today we’ll look at one of the most interesting, and I would say, confusing, aspects of short variable declarations. Short variable declarations … Unlike regular variable declarations, a short variable declaration may redeclare variables provided they were originally declared earlier in the same block (or the parameter lists if the block is the function body) with the same type, and at least one of the non-blank variables is new. As a consequence, redeclaration can only appear in a multi-variable short declaration.


Short variable declarations

Yesterday we saw how to define variables with var, but if you’ve ever actually used Go, you probably know that’s not actually the most common way to define variables. Let’s take a look at the alternative… Short variable declarations A short variable declaration uses the syntax: ShortVarDecl = IdentifierList ":=" ExpressionList . It is shorthand for a regular variable declaration with initializer expressions but no types: "var" IdentifierList "=" ExpressionList .


Continue statements

Let’s continue… haha See what I did there? Bleh, okay. Continue statements A “continue” statement begins the next iteration of the innermost enclosing “for” loop by advancing control to the end of the loop block. The “for” loop must be within the same function. ContinueStmt = "continue" [ Label ] . There’s not a lot necessary to say here. continue works very much like break. The scoping rules are essentially the same.

Get daily content like this in your inbox!

Subscribe