Is it possible in Go to call a function with named arguments? [duplicate]
Asked Answered
B

2

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?

Backfield answered 30/5, 2019 at 7:45 Comment(0)
C
8

There is no such thing like named arguments in go

Ci answered 30/5, 2019 at 8:4 Comment(3)
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!Backfield
Nothing illogical about the ask. Such option exists in python exists, and it makes the code self documenting in many situationsHandhold
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.Zaria
C
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

Chicalote answered 30/5, 2019 at 8:16 Comment(1)
I saw this repo, I preferred to avoid unnecessary packages. ThanksBackfield

© 2022 - 2024 — McMap. All rights reserved.