dongze8698 2018-12-23 08:16
浏览 55
已采纳

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?

  • 写回答

1条回答 默认 最新

  • donglu5728 2018-12-23 08:38
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥20 求用stm32f103c6t6在lcd1206上显示Door is open和password:
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法