duandaishi9268 2019-09-23 20:31
浏览 43
已采纳

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

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')

  • 写回答

2条回答 默认 最新

  • doufan6886 2019-09-23 21:12
    关注

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?