Skip to content

proposal: Go 2: require explicit variable shadowing #30321

@networkimprov

Description

@networkimprov

Branched from #377.

Problem

Unintended shadows are easy to create with := and cause nearly invisible bugs.

Go takes one of eight possible paths for a, b := f(), as each var is defined, assigned, or shadowed. One cannot tell which without searching prior code, so it's easy to write something that behaves incorrectly.

Proposal

Benefits Provided

a) eliminate bugs due to unintended := shadows
b) reduce the complexity of := statements (a, b := f() would have three paths)
c) no learning curve for the go vet changes
d) backwards compatibility

Changes to go vet and var:

  1. Let go vet flag implicit shadows, s := t.

  2. Let var s T or var s = t in the new scope silence go vet for intended shadows.

    x, err := Fa()
    if err != nil {
       var err error     // explicit shadow; not flagged by go vet
       y, z, err := Fb()
       ...
       x := 1            // implicit shadow: flagged by vet
    }
    
  3. Let var name allow redeclaration of the name within its scope, without creating a shadow. Python also permits this. (Not essential to (1) & (2), so could be omitted.)

    x, err := Fa()
    if err == nil {      // OR: if var err; err == nil 
       var err           // override shadowing in if-scope
       y, z, err := Fb() // no need for separate declarations of y & z
       ...
    }
    if err != nil { ... }
    

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions