Today we’re rounding out the list of scoping rules, with two more:
Declarations and scope
…
- 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.
- 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