How to give default value to function parameters

is there a way to give default value to function’s parameter
func sm(x float64, mu float64 = 2) (float64, float64) {
return (x, mu)
x := 1
s := sm(x)
// which returns (1, 2)

Unfortunately, Go does not support default parameters. However you can define your methods upon variadic functions.

Your above example can look like:

// a tricky case might be when you do something like this
// func sm(args ...float64) (float64, float64) {} here people
// can call your function just like this sm() which does not
// satisfy your function design that you mentioned above
// so we define it like this
func sm(x float64, args ...float64) (float64, float64) {
mu := 2
if len(args) > 0 {
    mu = args[0]

return (x, mu)
1 Like

what if there are more then 1 default parameter?

like instead of : func sm(x float64, mu float64 = 2)
use this defintion : func sm(x float64, mu float64 = 2, sigma float64 = 3)

and some times want to change this default value with user value

Same technique applies, as long as all arguments are of the same type.

Though I consider this a crutch.

Just use different named functions with a different set of arguments.


thanks Norbet and Ashish

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.