liveBook · Manning

Shadowing

As explained in 100 Go Mistakes and How to Avoid Them

A shadowed variable is a variable declaration that hides another variable with the same name in an enclosing scope.

Shadowing occurs when a variable is redeclared in an inner block, hiding a variable with the same name in an enclosing scope. In Go, this commonly happens when := is used inside if or else blocks. section 2.1

The client that remains nil

Suppose client is declared outside an if statement. Using client, err := inside either branch creates a new client variable rather than assigning the outer one. The inner variable is logged and used, so the code compiles, but client remains nil after the conditional. section 2.1

var client *http.Client                          #1
if tracing {
    client, err := createClientWithTracing()     #2
    if err != nil {
        return err
    }
    log.Println(client)
} else {
    client, err := createDefaultClient()         #3
    if err != nil {
        return err
    }
    log.Println(client)
}
// Use client

The listing traces the outer client declaration and the two inner declarations that hide it. section 2.1

Choose a correction based on how the values and error handling should be organized:

  • Declare a temporary variable such as c inside each branch, then assign c to the outer client variable. section 2.1
  • Declare err before the conditional and use = instead of :=, assigning directly to the existing client variable. section 2.1
  • Use direct assignment when common error handling can follow the if/else statement; this performs one assignment and can improve readability. section 2.1
  • Avoid shadowing when it could make readers reference the wrong variable, but apply the rule pragmatically rather than forbidding it universally. section 2.1 section 2.17

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Defines scope and shadowing, traces a nil result, and compares temporary-variable and direct-assignment fixes.
Examples
Uses tracing-dependent HTTP client creation to show hidden declarations and two corrected initialization patterns.
What it assumes
Assumes familiarity with Go blocks, variables, conditionals, and error handling while defining scope from its reference behavior.
What you can do after
Diagnose hidden declarations and choose temporary-variable or direct-assignment fixes for conditional initialization.
How it connects
Connects lexical scope with short variable declarations, assignment, conditionals, and error handling.

Also explained in

Compare how 4 books explain shadowing →

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.