4

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.

thwd
  • 23,956
  • 8
  • 74
  • 108

2 Answers2

2

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)
}
nmichaels
  • 49,466
  • 12
  • 107
  • 135
  • it's pretty sad that there's no integrated support for optional arguments in Go. I solved my problem by using a variadic function. Thank you. – thwd Dec 30 '11 at 20:05
  • Mainstream languages like C, Java, C++ don't support optional args neither, AFAICS. – zzzz Dec 31 '11 at 10:14
  • @jnml, C++ can fake it with overloaded function prototypes. Many mainstream languages, like Python, do support default values for function parameters. That's actually what we're talking about since I think all of those (I don't know Java) and certainly most mainstream languages do support variadic functions. – nmichaels Jan 03 '12 at 18:24
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})
Sonia
  • 27,135
  • 8
  • 52
  • 54
  • I like this approach, but what about when the default value for bar needs to be something other than zero, and likewise the default value for foo is some arbitrary string? I get a bit irritated with Go when I can't find simple ways to resolve cases like this. – jsdw Jul 06 '13 at 13:32