12

I want to call a function in Go, and attach to the argument values the argument names

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

func main() {
  result := sum(a=4, b=5) // result == 9
}

Is it possible?

Netanel.R
  • 153
  • 1
  • 7

2 Answers2

8

There is no such thing like named arguments in go

Roman Kiselenko
  • 43,210
  • 9
  • 91
  • 103
  • you refer to `a` and `b` as local arguments, I mentioned them as the arguments in the function signature. But I understand, there is no such thing named arguments in go...Thanks! – Netanel.R May 30 '19 at 08:19
  • 12
    Nothing illogical about the ask. Such option exists in python exists, and it makes the code self documenting in many situations – Espresso Jun 28 '20 at 19:24
  • Specifying the parameter when calling a function makes it much more clear what information is being passed and there's no harm in letting the compiler allow it if the parameters are still ordered properly. Initializing variables in the parameters may not be OK, but a=4; b=5; result := sum(a=a, b=b) is what I would like to see possible. – Michael Fulton Jan 03 '21 at 18:42
3

At the moment Go does not have a way to use named argument in functions. If you really need to use named arguments you can try this library go-named-params

sanoJ
  • 2,935
  • 2
  • 8
  • 18