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



