-
Notifications
You must be signed in to change notification settings - Fork 18.7k
Description
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:
-
Let go vet flag implicit shadows,
s := t. -
Let
var s Torvar s = tin 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 } -
Let
var nameallow 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 { ... }