英文:
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 > b {
a, b = b, a
}
switch true {
case x < a:
return a
case x > 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 > b {
a, b = b, a
}
switch true {
case x < a:
return a
case x > 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论