Arithmetic expression in case

I want use case statement instead of switch for arithmetic comparison. Could you please let me know what’s wrong with the following code??

package main
import "fmt"
func main(){                                                                                                                                                            
        a := 2                                                                                                                                                                                                                                                                                                          
        switch a {                                                                                                                                                      
        case a < 5 :                                                                                                                                                    
                fmt.Println("value is less than 5")                                                                                                                               
        }                                                                                                                                                               
}

You can’t switch on expressions, only on constants. And you can’t switch on integers (see https://tour.golang.org/flowcontrol/9)

Do this:

package main

import "fmt"

func main() {
	a := 2
	if a < 5 {
		fmt.Println("value is less than 5")
	}
}

I just found the answer to my question over here

https://www.dotnetperls.com/switch-go

So my code would become,

package main
import "fmt"
func main(){
        a := 2
        switch {
        case a < 5 :
                fmt.Println("value is 2")
        }
}

This works

Be aware though, that this is only syntactic sugar for nested if/else statements, expressions are evaluated and compare in order given, there is no way the compiler were able to optimize that into a jump table.

2 Likes

Interesting, could you please provide some links supporting that?

I’ve never heard of jump table before, but just read now online, they say switch statements are relatively faster than if/else because of jump tables.

Blockquote

Switch beeing faster is only true when switching over a value rather than over expressions.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.