Additional arguments?

Is there a way to declare an argument as โ€œoptionalโ€ in the Go programming language?

An example of what I mean:

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

I want the bar parameter to be optional and defaults to 0 if nothing went wrong.

 doSomething("foo") 

will be the same as

 doSomething("foo",0) 

I cannot find anything about this in the official function documentation.

+4
source share
2 answers

I do not believe that Go supports optional arguments for functions, although you can fake it with variadic functions . C approach, if you don't want to do this, is to pretend that the language supports currying:

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

Another way to fake this is to convey structure.

 type dsArgs struct { foo string bar int } func doSomething(fb dsArgs) bool { //... } 

Then

 doSomething(dsArgs{foo: "foo"}) 

coincides with

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

Source: https://habr.com/ru/post/1388649/


All Articles