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?
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.
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
}