可选参数?

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

Optional arguments?

问题

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

我指的是以下示例:

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

我希望参数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:

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

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

doSomething("foo")

would be the same as

doSomething("foo",0)

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

答案1

得分: 2

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

func doSomethingNormally(foo string) bool {
    doSomething(foo, 0)
}
英文:

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:

func doSomethingNormally(foo string) bool {
    doSomething(foo, 0)
}

答案2

得分: 0

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

type dsArgs struct {
    foo string
    bar int
}

func doSomething(fb dsArgs) bool {
    //...
}

然后

doSomething(dsArgs{foo: "foo"})

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

是一样的。

英文:

Another way to fake it is to pass a struct.

type dsArgs struct {
    foo string
    bar int
}

func doSomething(fb dsArgs) bool {
    //...
}

Then

doSomething(dsArgs{foo: "foo"})

is the same as

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:

确定