liveBook · Manning

Scope

As explained in 100 Go Mistakes and How to Avoid Them

Scope is the region of source code in which a variable name binding is valid and can be referenced.

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

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains block bindings, shadowing, closure capture, and benchmark observability through concrete Go examples.
Examples
Uses HTTP client branches, popcount benchmarks, and goroutines launched inside a loop.
What it assumes
Assumes familiarity with Go blocks, short declarations, functions, closures, loops, and goroutines.
What you can do after
Diagnose shadowing and closure-capture bugs, then choose assignments or per-iteration values that preserve the intended binding.
How it connects
Connects variable shadowing with short variable declarations, closures, goroutines, loop variables, and compiler optimizations.

Also explained in

Compare how 21 books explain scope →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.