Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
160 views
in Technique[技术] by (71.8m points)

Optional params in Go?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...