Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional Parameters in Go?

Tags:

overloading

go

Can Go have optional parameters? Or can I just define two different functions with the same name and a different number of arguments?

like image 712
devyn Avatar asked Jan 09 '10 02:01

devyn


People also ask

Can Go have optional parameters?

Go doesn't support optional function parameters. This was an intentional decision by the language creators: One feature missing from Go is that it does not support default function arguments.

How do you make an optional parameter in Golang?

A nice way to achieve something like optional parameters is to use variadic args. The function actually receives a slice of whatever type you specify. But only for the same type of params :( @JuandeParras Well, you can still use something like ...

What is Variadic function in Golang?

A variadic function is a function that accepts a variable number of arguments. In Golang, it is possible to pass a varying number of arguments of the same type as referenced in the function signature.

Can you pass functions as parameters in Go?

Yes Go does accept first-class functions. See the article "First Class Functions in Go" for useful links. Please expand on this response some; include an example, link to reference (e.g. actual reference), etc.


3 Answers

Go does not have optional parameters nor does it support method overloading:

Method dispatch is simplified if it doesn't need to do type matching as well. Experience with other languages told us that having a variety of methods with the same name but different signatures was occasionally useful but that it could also be confusing and fragile in practice. Matching only by name and requiring consistency in the types was a major simplifying decision in Go's type system.

like image 115
Andrew Hare Avatar answered Oct 20 '22 21:10

Andrew Hare


A nice way to achieve something like optional parameters is to use variadic args. The function actually receives a slice of whatever type you specify.

func foo(params ...int) {
    fmt.Println(len(params))
}

func main() {
    foo()
    foo(1)
    foo(1,2,3)
}
like image 319
Ferguzz Avatar answered Oct 20 '22 22:10

Ferguzz


You can use a struct which includes the parameters:

type Params struct {
  a, b, c int
}

func doIt(p Params) int {
  return p.a + p.b + p.c 
}

// you can call it without specifying all parameters
doIt(Params{a: 1, c: 9})

The main advantage over an ellipsis (params ...SomeType) is that you can use the param struct with different parameter types.

like image 224
deamon Avatar answered Oct 20 '22 22:10

deamon