-1

I know that there aren't any optional params in the latest version of Go. But there are quite a lot cases when they are really helpful.

Consider oversimplified example:

func getFullName(firstName string, lastName string, maybeMiddleName func() (bool, string)) string {
    if ok, middleName:= maybeMiddleName(); ok {
        return firstName + " " + middleName + " " + lastName
    }

    return firstName + " " + lastName
}

That looks fine enough, thought requires a lot verbosity on a client side: whenever middleName is absent or present, one has to pass func() (bool, string) { return false, nil } inside. It could be just (false, nil) if Go would support tuples as input parameters, but it doesn't: you can return (pairs, or, even, more), but not take them as expected input.

One could argue that the nil might be taken as an indication of absence. I disagree: no nil's allowed to overflood any reliable codebase.

The other option I see even more verbouse: anon structs like func(maybeMiddleName struct{ ok bool; middleName string; }) ..., which forces a caller of this method to write even more redundant code each and every time.

But I am new to Go and still feel like there might be a better way. Is there?

Zazaeil
  • 3,900
  • 2
  • 14
  • 31
  • 1
    The idiomatic and short solution (which you rejected outright) is to pass zero values for absent parameters. Embrace the zero value. Nil is much more useful in Go than in other languages. You can also make two functions that then call a third, unexported function (again, passing zero values for unused parameters). – Peter Dec 23 '18 at 09:06
  • @Peter, can you please post a proper answer demonstrating additional power of nil in Go? – Zazaeil Dec 23 '18 at 09:09
  • Be aware of `nil` for interfaces and slices, you never now for sure what the `== nil` check actually results in. And keep in mind that you can neither create a pointer of a return value on the fly, nor for a `string`, an `int` or any other simple type literal, making the work with `nilable` arguments somewhat clumsy. – NotX Mar 26 '21 at 21:52

1 Answers1

1

But I am new to Go and still feel like there might be a better way. Is there?

I'm affraid to say not.There isn't another way.

Mostafa Solati
  • 1,235
  • 2
  • 13
  • 33