Go Reference ยท Concepts
Go scope and shadowing
Reference for Go scope: universe, package, file and block scopes, how := shadows variables, the shadowed err pitfall, shadowing builtins, and how to avoid bugs.
The scope of an identifier is the region of source code in which it can be used. Go scopes are lexical and based on blocks, which are the pieces of code between braces, plus a few implicit blocks. A declaration is visible from the point it is declared to the end of the innermost block that contains it. An inner declaration with the same name shadows the outer one: inside the inner block the name means the new thing, and the outer variable is untouched.
Shadowing is legal and sometimes useful, but it is also the source of a classic bug: writing := where you meant =. The compiler accepts the code, an inner variable is created, and the outer variable keeps its old value.
x := 1 if true { x := 2 // a new x that exists only inside this block _ = x } fmt.Println(x) // 1
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
Go has these scopes, from widest to narrowest:
| Scope | What lives there |
|---|---|
| Universe | Predeclared identifiers: int, string, true, false, nil, len, append, any, error, iota, and so on. |
| Package | Every top-level declaration in every file of the package (functions, types, variables, constants). |
| File | Imported package names. An import is visible only in the file that contains it. |
| Function | Labels (for goto, break label, continue label). Parameters and results are in the function's outermost block. |
| Block | Everything declared with var, const, type or := inside { ... }. |
Implicit blocks: the whole source is the universe block; each package, file, if, for and switch statement has its own block; each clause in a switch or select is a block of its own. A type parameter's scope is the function or type that declares it.
Where a name starts and stops: a variable declared inside a function is in scope from the end of its declaration (so x := x + 1 on the right-hand side sees the outer x) to the end of its block. Package-level names are in scope in the entire package, in any order.
:= rule. At least one name on the left must be new in the current block. Names that already exist in the same block are assigned; names that exist only in an outer block are shadowed by a new variable.
Errors and edge cases:
- An unused local variable is a compile error (
declared and not used). An unused import is one too. - Redeclaring a name in the same block fails with
no new variables on left side of :=orredeclared in this block. - A package name (
fmt) can be shadowed by a variable, and thenfmt.Printlnstops compiling.
Usage notes
- Shadowed
erris the big one. Inif x, err := f(); err != nil { ... }theerrlives only in theif. That is fine. The bug appears when an inner:=hides anerryou later return. - Use
=after a plainvar. Declaringvar err errorfirst and using=inside blocks avoids accidental shadowing. - Tools.
go vetdoes not report shadowing by default. Theshadowanalyzer ingolang.org/x/toolsand linters such asgovetwithcheck-shadowingdo. - Do not shadow builtins. Variables named
len,new,copy,max,min,stringorerrorcompile, and then confuse every reader. Since Go 1.21minandmaxare builtins, so older code that defined those names as functions still works but shadows them. - Closures capture variables, not values. A closure sees the variable at the scope where it was written, so shadowing after the closure was created does not affect it. See Loop variable semantics.
- Short blocks are a feature. Keep the scope of a variable as small as it can be:
if v, ok := m[k]; ok { ... }. - Methods and fields are not in scope as bare names. They are reached through a selector (
x.name), so a field and a local variable can share a name.