有没有办法在Go语言中避免包含无法到达的返回语句?

huangapple go评论80阅读模式
英文:

Is there any way to get around including an unreachable return statement in go?

问题

我有以下函数:

func fitrange(a, x, b int) int {
    if a > b {
        a, b = b, a
    }
    switch true {
    case x < a:
        return a
    case x > b:
        return b
    default:
        return x
    }
}

Go编译器抱怨“函数结束时没有返回语句”,尽管通过switch语句的每个可能路径都返回一个值。除了在函数末尾添加一个虚拟的return语句之外,是否有其他方法可以解决这个问题?

英文:

I have the following function:

func fitrange(a, x, b int) int {
    if a &gt; b {
        a, b = b, a
    }
    switch true {
    case x &lt; a:
        return a
    case x &gt; b:
        return b
    default:
        return x
    }
}

The go compiler complains that the "function ends without a return statement" even though every possible path through the switch statement returns a value. Is there any way to get around this other than adding a dummy return statement at the end of the function?

答案1

得分: 10

删除default情况,并在switch之后返回x。

像这样:

func fitrange(a, x, b int) int {
    if a > b {
        a, b = b, a
    }
    switch true {
    case x < a:
        return a
    case x > b:
        return b
    }
    return x
}
英文:

Remove the default case all together and return x after the switch.

Like:

func fitrange(a, x, b int) int {
    if a &gt; b {
        a, b = b, a
    }
    switch true {
    case x &lt; a:
        return a
    case x &gt; b:
        return b
    }
    return x
}

答案2

得分: 8

不要在最后添加一个返回,你也可以通过添加一个panic来安抚编译器。这不是一个坏主意,因为如果你的代码包含一个bug,并且那个"unreachable"行被执行到,你的程序将会立即停止,而不是继续执行可能错误的答案。

英文:

Instead of adding a return at the end, you can also pacify the compiler by adding a panic. It's not a bad idea because if your code contains a bug and that "unreachable" line is ever reached, your program will halt promptly rather than plow ahead with a potentially wrong answer.

huangapple
  • 本文由 发表于 2012年6月19日 03:59:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/11090157.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定