go-tools icon indicating copy to clipboard operation
go-tools copied to clipboard

staticcheck: detect shadowing of named returns

Open florianl opened this issue 1 year ago • 5 comments

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
}

florianl avatar Apr 22 '24 18:04 florianl

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?

dominikh avatar Apr 22 '24 18:04 dominikh

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
}

florianl avatar Apr 23 '24 06:04 florianl

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.

arp242 avatar May 26 '24 22:05 arp242

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

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

ccoVeille avatar May 26 '24 23:05 ccoVeille