Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 849
Matt Avatar asked Dec 03 '22 03:12

Matt


1 Answers

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
}
like image 118
Ryan Avatar answered Jan 12 '23 00:01

Ryan