doutenggu4070 2019-05-09 06:55
浏览 45
已采纳

为什么我们真的需要Golang中的“失败”? 哪个用例使Golang创作者首先将其包括在内? [关闭]

"fallthrough" used in switch block, will transfer the execution to the next case's first statement without evaluating the next case statement. In real world, why do we need it? If at all we had to execute the next case block, we could have combined that code in the evaluated case already. Why do we really need "fallthrough"? What is its significance?

  • 写回答

1条回答 默认 最新

  • dtsps2098 2019-05-09 07:41
    关注

    Combining the 2 cases into a single one is not equivalent with 2 separate cases where the first ends with a fallthrough.

    switch {
    case conditionA:
        statementA()
        fallthrough
    case conditionB:
        statementB()
    }
    

    In this example statementB() is executed if conditionA evaluates to false and conditionB evaluates to true. If you would combine them:

    switch {
    case conditionA:
        statementA()
        statementB()
    }
    

    Here statementB() is executed only if conditionA evaluates to true, and that's all. This is not the same as the first example.

    Obviously you can't include conditionB in the case expression as statementA must not depend on conditionB (if we want an equivalent transformation).

    All in all, this is just a "tool" which you may or may not use. You can achieve the same in other ways (if statement), but this may be convenient in some cases.

    In many languages you are required to use a break statement if you don't want this "fallthrough" behavior, so many people might get accustomed to it. Although most often switches are used not to fallthrough, so this became the default in Go, but if you need the other logic, you have the option with fallthrough.

    The question Why do we really need "fallthrough"? is equivalent in those languages with Why do we need "break" to be optional and not mandatory?

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

报告相同问题?

悬赏问题

  • ¥15 对于这个复杂问题的解释说明
  • ¥50 三种调度算法报错 采用的你的方案
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败