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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…