Optional params in Go?

梦想与她 提交于 2019-12-14 03:34:28

问题


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?


回答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.



来源:https://stackoverflow.com/questions/53902172/optional-params-in-go

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!