可选参数?

huangapple go评论191阅读模式
英文:

Optional arguments?

问题

在Go编程语言中,有没有一种方法可以将参数声明为“可选”的?

我指的是以下示例:

  1. func doSomething(foo string, bar int) bool {
  2. //...
  3. }

我希望参数bar是可选的,如果没有传递任何值,则默认为0

doSomething("foo")将等同于doSomething("foo", 0)

我在官方函数文档中找不到关于这个问题的任何信息。

英文:

Is there a way to declare an argument as "optional" in the Go programming language?

Example of what I mean:

  1. func doSomething(foo string, bar int) bool {
  2. //...
  3. }

I want the parameter bar to be optional and default to 0 if nothing is passed through.

  1. doSomething("foo")

would be the same as

  1. doSomething("foo",0)

I'm unable to find anything about this matter in the official documentation about functions.

答案1

得分: 2

我不相信Go支持函数的可选参数,尽管你可以通过可变参数函数来模拟。如果你不想这样做,可以采用C语言的方法,假装语言支持柯里化:

  1. func doSomethingNormally(foo string) bool {
  2. doSomething(foo, 0)
  3. }
英文:

I don't believe Go does support optional arguments to functions, though you can fake it with variadic functions. The C approach, if you don't want to do that, is to pretend the language supports currying:

  1. func doSomethingNormally(foo string) bool {
  2. doSomething(foo, 0)
  3. }

答案2

得分: 0

另一种伪造的方法是传递一个结构体。

  1. type dsArgs struct {
  2. foo string
  3. bar int
  4. }
  5. func doSomething(fb dsArgs) bool {
  6. //...
  7. }

然后

  1. doSomething(dsArgs{foo: "foo"})

  1. doSomething(dsArgs{foo: "foo", bar: 0})

是一样的。

英文:

Another way to fake it is to pass a struct.

  1. type dsArgs struct {
  2. foo string
  3. bar int
  4. }
  5. func doSomething(fb dsArgs) bool {
  6. //...
  7. }

Then

  1. doSomething(dsArgs{foo: "foo"})

is the same as

  1. doSomething(dsArgs{foo: "foo", bar: 0})

huangapple
  • 本文由 发表于 2011年12月31日 02:54:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/8682919.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定