Can Go have optional parameters? Or can I just define two different functions with the same name and a different number of arguments?
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.
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 ...
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.
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.
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.
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)
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With