Distinguish universe, package, file and block scope
Distinguish universe, package, file and block scope
Go has several levels of scope. The universe block contains predeclared names such as len and int. A top-level variable belongs to the package block and is visible in other files of the same package. Imported package names belong to the importing file. Local variables belong to their enclosing lexical scopes.
package main
import ( "fmt")
var limit = 5
func current() int { return limit }func main() { values := []int{1, 2, 3} fmt.Println(current(), len(values)) { limit := 1 fmt.Println(limit) } fmt.Println(limit)}current reads the package variable. len is a predeclared function and fmt is a file-local imported name. The inner limit hides the package name only within its block. Scope is distinct from exported visibility: an unexported package declaration is still accessible across files of its own package.
Expected output:
5 315Avoid hiding predeclared names
package main
import ( "fmt")
func main() { { len := 42 fmt.Println(len) } fmt.Println(len("go"))}The first len is an integer variable and cannot be called. After the block ends the built-in len is visible again. Prefer a descriptive name such as itemCount. In a multi-file package, a file that uses fmt must import it itself; imports in other files do not supply that name.
Expected output:
422Try it locally
Declare a package variable base=4, and inside main declare a local step=3. Print base+step and len("Go").
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Scope and closures 02: Distinguish universe, package, file and block scope
Check the lesson objective before moving on.
Which scope contains the built-in len?
File a.go imports fmt. What must b.go do to use fmt.Println?