dominikh / go-tools

Staticcheck - The advanced Go linter
https://staticcheck.dev
MIT License
6.01k stars 361 forks source link

staticcheck: detect shadowing of named returns #1524

Open florianl opened 2 months ago

florianl commented 2 months ago

staticcheck should detect the shadowing of named returns.

In the following example, the function foo() uses the named return err error. In this case, the named return is shadowed by err := bar().

func bar() error {
 return nil
}

func foo() (err error) {
  err := bar()
  return
}
dominikh commented 2 months ago

Note that the provided example doesn't compile, because that's not shadowing but trying to redeclare. And if it had worked, it would've been an unused variable and also hadn't compiled.

Do you have a closer-to-reality example you'd like to see flagged by Staticcheck?

florianl commented 2 months ago

This is the example from the Go specification (last example in the Return statements section):

func f(n int) (res int, err error) {
    if _, err := f(n-1); err != nil {
        return  // invalid return statement: err is shadowed
    }
    return
}
arp242 commented 1 month ago

Better to flag all naked returns IMHO. That's more opinionated, but as far as I know there's fairly wide agreement that they should pretty much always be avoided. That's #170.

ccoVeille commented 1 month ago

I'm using revive to detect "naked return", aka "bare return"

https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#bare-return