Scope is the region of source code where a variable name binding is valid and can be referenced. In Go, a declaration in an inner block can shadow a name from an outer block, creating a different binding rather than updating the original. section 2.1
The shadowed client
A common mistake is using := inside branches after declaring client outside them. Each branch creates an inner client, so the outer client remains nil. Use temporary variables and assign them back, or declare err and use = to update the existing client; the latter also supports shared error handling after the branches. section 2.1
const m1 = 0x5555555555555555
const m2 = 0x3333333333333333
const m4 = 0x0f0f0f0f0f0f0f0f
const h01 = 0x0101010101010101
func popcnt(x uint64) uint64 {
x -= (x >> 1) & m1
x = (x & m2) + ((x >> 2) & m2)
x = (x + (x >> 4)) & m4
return (x * h01) >> 56
}
A benchmark illustrates another scope distinction: v is local to the benchmark function, while global is package-level. Assigning through both keeps the tested result observable without paying the global-write cost on every iteration. section 11.8.3
Scope also determines what concurrent closures capture:
- A goroutine closure that reads a loop variable declared outside its body observes the variable as it changes, producing nondeterministic output. section 9.3
- Create a per-iteration local variable before starting the goroutine, or pass the iteration value as a function argument; both approaches fix the value each closure uses. section 9.3




















