转到:调用函数时如何使用命名参数?

How can I invoke a function while using named arguments?

(If it's unclear what named arguments are, here's an example of using them in Python)

Example of what I'd like to do:

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

func main() {
  c := Add(a: 1, b:3)
  return c
}

However, the above gives me the error:

unexpected :, expecting comma or )

(it's referring to the ':' right after the 'a')

Go does not have named arguments. The closest thing I know of in Go to named arguments is using a struct as input. So for your example you could do -

type Input struct {
  A int
  B int
}

func Add(in Input) int {
  return in.A + in.B
}

func main() {
  c := Add(Input{A: 1, B: 3})
  return c
}

In brief: the Go language does not support named args but IDEs do (see below).

I agree that named arguments could be useful in Go. It could help avoid bugs. For example, just yesterday my tests picked up a bug where the source and dest. parameters to copy() (Go built-in function) were back to front.

However, there are probably hundreds of useful language features that Go could have. We try to avoid adding non-essential features to the language to keep things simple. Once you've used Go for a large project you will greatly appreciate how much simpler things are compared to other languages. (I have used more than a dozen languages professionally and Go is by far the least annoying.)

But actually you can have named arguments if your IDE supports it. For example, I use GoLand and when you enter the arguments to a function it shows the parameter name (in light gray) in-line with a colon before the value. This is even better than what you are used to as you don't even have to type the name!