Variable Shadowing in Inner Scope

declaration of "err" shadows declaration at outer scope (govet)

Quick Answer

You are declaring a new variable with the same name as one in an outer scope, hiding the outer variable. Use = instead of := to reuse the outer variable.

Why This Happens

Variable shadowing occurs when := inside an inner scope creates a new variable with the same name as one in the outer scope. The inner variable hides the outer one, meaning changes to the inner variable do not affect the outer one. This is a common source of bugs, especially with err variables.

The Problem

func readConfig() (string, error) {
    var err error
    var config string
    if true {
        config, err := loadFile() // shadows outer err
        _ = config
        _ = err
    }
    return config, err // err is always nil
}

The Fix

func readConfig() (string, error) {
    var err error
    var config string
    if true {
        config, err = loadFile() // reuses outer err
    }
    return config, err
}

Step-by-Step Fix

  1. 1

    Identify the shadow

    Find the := that creates a new variable shadowing the outer one. Linters will point out the exact line.

  2. 2

    Determine the intent

    Decide if you wanted to reassign the outer variable or genuinely create a new one.

  3. 3

    Use = instead of :=

    If you want to modify the outer variable, change := to = and ensure the variables are already declared.

Bugsly catches this automatically

Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.

Try Bugsly free