Optional func/method args

Hi,

I was wondering what the best way is to allow optional arguments when calling a function/method - the idea really is that I don’t want to force a person to set values that’d be used by something like time.Sleep inside the function that’s being called …

func f(delay time.Duration) {
  time.Sleep(delay)
  fmt.Println("I slept for", delay)
}

If I want to call the func f() I will have to provide a delay f(time.Duration(0)), even if I don’t want / need to as the default value for time.Duration is a int64(0) and if I don’t want to set a delay, then 0 is fine by me.

Any suggestions? Maybe one that isn’t use variadic function arg as the args may be of different “type”, e.g. mix of multiples of (optional) delays + optional func(), etc. ?

Here’s an example: https://play.golang.org/p/xSeiaWwh2cX

Thanks!
Alex

3 Likes

I’d provide 2 functions, f and fDelayed:

func f() {
  fDelayed(time.Duration(0))
}

func fDelayed(delay time.Duration) {
  time.Sleep(delay)
  fmt.Println("I slept for", delay)
}
2 Likes

Dealing with Optional Parameters in Go

2 Likes

Thanks @GreyShatter and @NobbZ!

Seems like it’s not quite that easy, especially not if you have potentially 4-5 optional args.

2 Likes

You can use a map argument as an alternative to variadic functions.

func f(arg map[string]YourType) {
}

This way, your user can send in labelled input or simply nil as the input.

f(nil)
f(map[string]YourType{ "delay" = 4*time.Duration}) 
f(map[string]YourType{ "delay" = 4*time.Duration, "acceleration" = 10.time.Duration, ... }) 
--- cleaner ---
options = map[string]YourType {
    "delay" = 4*time.Duration,
    ...
}
f(options)
---------------

Go does not have full optional parameters so if you want to offer a no-argument parameter as one of the option, @NobbZ method would be the best.

2 Likes

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