nonamedreturns icon indicating copy to clipboard operation
nonamedreturns copied to clipboard

Option to allow naming of return values, but forbid use of them

Open silverwind opened this issue 1 year ago • 4 comments

Names return values are useful for documentation, but problematic when those variables are actually used because of mutation. I would propose a option to the linter to allow naming return values but forbid their use.

Pass

func add(a, b int) (sum int) {
  return a + b
}
func add(a, b int) int {
  return a + b
}
func add(a, b int) int {
  var sum int
  sum = a + b
  return sum
}

Fail

func add(a, b int) (sum int) {
  sum = a + b // error: do not use named return variables
  return sum
}

silverwind avatar Jul 12 '23 09:07 silverwind

What's the real difference between

func add(a, b int) int {
  var sum int
  // some other code
  // ...
  // ...
  sum = a + b
  return sum
}

and

func add(a, b int) (sum int) {
  // some other code
  // ...
  // ...
  sum = a + b // error: do not use named return variables.
  // Question: what's the real difference? why it should be forbidden?
  return sum
}

?

I can see in both cases, the "sum" is declared explicitly, I do not think the "Fail" one is harmful or it would cause any real problem.

wxiaoguang avatar Jul 12 '23 14:07 wxiaoguang

Technically they are equal. I guess the only benefit of the var variant is that it may be easier to understand for someone coming from languages that do not have named return values.

One benefit of allowing optional naming is that (int, int, int) becomes more readable with names, e.g. (x, y, z int). But of course the same can be achieved with a var statement.

Preferring a functional code style myself, I do prefer for mutable variables to be explicitely declared which the var statement achieves.

silverwind avatar Jul 12 '23 17:07 silverwind

The difference is that function signatures are a form of documentation often revealed by editors. e.g.

image

vs.

image

glacials avatar Aug 06 '23 19:08 glacials

The main problem with named return values is using naked returns.

func add(a, b int) (sum int) {
  sum = a+b
  return
}

In my opinion it would be actually better to actually require named returns when a function returns two or more values of the same or similar type. You don't need named params for (*Foo, error) but you do for (int, int64, int).

kke avatar Nov 29 '23 08:11 kke