Go中的可选参数? [英] Optional params in Go?

查看:164
本文介绍了Go中的可选参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道最新版本的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.

考虑过度简化的示例:

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

    return firstName + " " + lastName
}

这看起来已经足够好了,思考需要在客户端进行很多冗长的操作:每当middleName不存在或存在时,都必须在内部传递func() (bool, string) { return false, nil }.如果Go支持元组作为输入参数,则可能只是(false, nil),但事实并非如此:您可以返回(pairs, or, even, more),但不能将其作为预期输入.

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.

一个人可能会争辩说nil可能被认为是缺席的征兆.我不同意:不允许nil淹没任何可靠的代码库.

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.

我看到的另一种选择更加麻烦:func(maybeMiddleName struct{ ok bool; middleName string; }) ...这样的匿名结构,它迫使该方法的调用者每次都编写更多的冗余代码.

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.

但是我对Go还是陌生的,仍然觉得可能会有更好的方法.有吗?

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

推荐答案

但是我对Go还是陌生的,但仍然觉得可能会有更好的方法.是 在那里吗?

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.

这篇关于Go中的可选参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆