Scope within functions

June 28, 2023

Today we’re rounding out the list of scoping rules, with two more:

Declarations and scope

  1. The scope of a constant or variable identifier declared inside a function begins at the end of the ConstSpec or VarSpec (ShortVarDecl for short variable declarations) and ends at the end of the innermost containing block.
  2. The scope of a type identifier declared inside a function begins at the identifier in the TypeSpec and ends at the end of the innermost containing block.

In short, constants, variables, and types defined within functions are in scope until the end of the current block (which may be the function itself, or any other block). This should be pretty intuitive, but let’s consider a couple examples to be sure.

func main() {
	const world = "World" // Scope of 'world' begins at the '=' sign
	fmt.Println("Hello", world)
} // Scope of 'world' ends here
func applyDiscount(price int) int {
	if price > 100 {
		newPrice := price-10 // Scope of 'newPrice' begins at ':='
		return newPrice
	} // Scope of 'newPrice' ends here
}

Quotes from The Go Programming Language Specification Version of December 15, 2022


Share this

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

Unsure? Browse the archive .

Related Content


The universe and package blocks

Let’s now dive into the specific scoping rules in Go. There are 8 rules here, and we’ll take one or two per day… Declarations and scope … Go is lexically scoped using blocks: The scope of a predeclared identifier is the universe block. The “universe block”, which encompasses all Go source text, only contains the predeclared identifiers defined in the specification. Specifically, these identifiers are the names of predeclared types, the constants true, false, and iota, the zero value nil, and the built-in functions.


Where declarations are allowed

First, a big thanks to everyone who showed up for yesterday’s first Boldly Go Live stream. We had some audio problems, which I promise to fix before the next one. But otherwise it was a success, with some great discussion. You can catch the replay if you missed it. Here we are at the formal description of declaration syntax. Declarations and scope … Declaration = ConstDecl | TypeDecl | VarDecl .


Representability

We’ve learned about types, type identity, and type assignability. But you may recall a bit of a discussion about some of the esoteric features of constants in Go. Namely, they can be untyped, and they don’t overflow. So how do we know if a constant can be represented faithfully by a particular type? We finally have the answer, in all its detailed glory: Representability A constant x is representable by a value of type T, where T is not a type parameter, if one of the following conditions applies:

Get daily content like this in your inbox!

Subscribe