Switch statement in Go
The switch statement is a controlled-based statement just like the if-else statements but they vary a lot when it comes to the syntax.
In switch statements, we make use of the switch keyword to compare a variable to different values, unlike the if-else statements where to compare a variable we would have to write multiple if keywords. The switch statement is a multiway branch statement that in turn provides us with an easy way to transfer the flow of execution to different parts of code based on the value.
Switch Statement in Go
When we compare the switch statements that Go makes use of to the switch statements present in C or Java, then we can comfortably say that Go switch statements are more flexible in nature. The flexibility comes from different options and features that the switch statements in Go provide us with instead of the general form of switch statements that you notice in languages like C or Java.
The general form of a switch statement in Go look something like this:
switch var1 {
case val1:
....
case val2:
....
default:
....
}
In the above format, we can notice that we are using the switch keyword that is followed by var1, which denotes a variable that can be of any type you want, and the val1, val2,... are possible values of var1. These values don't have to be constants or integers, but they must have the same type, or expressions evaluating to that type. The opening { braces have to be on the same line as the switch keyword. The ellipses ... here means that after the case statement, multiple statements can follow without being surrounded by {}, but braces are allowed.
Let's consider a simple example that will help in understanding the general form shown above.
Example: Go Switch Statement
This example uses a switch statement with multiple cases that execute only if the case matches.
package main
import (
"fmt"
)
func main() {
var x int = 2
switch x {
case 1:
fmt.Println("Case 1")
case 2:
fmt.Println("Case 2")
case 3:
fmt.Println("Case 3")
default:
fmt.Println("IDK")
}
}
Case 2
It is good to note that if there is only one statement in a specific case then it can be placed on the same line as of the case ... keyword.
Consider an example depicting the scenario.
Example 2: Go Switch with one Statement
If switch cases have a single statement only then can be written in the same line.
package main
import (
"fmt"
)
func main() {
var x int = 2
switch x {
case 1:fmt.Println("Case 1")
case 2:fmt.Println("Case 2")
case 3:fmt.Println("Case 3")
default:
fmt.Println("IDK")
}
}
Case 2
Another important variation of the switch statement that is possible in Go is that if the case statements end with a return statement, then there has to be a return statement after the } of the switch statement.
Example 3: Switch Statement with return keyword
We can use a return statement in the switch case to return a value.
package main
import (
"fmt"
)
func main() {
ans := WhiteSpace('\t')
fmt.Println(ans)
}
func WhiteSpace(c rune) bool {
switch c {
case ' ', '\t', '\n', '\f', '\r':
return true
}
return false
}
true
Example 3: Switch Case with multiple values
Go switch statements can also have more than one value in a single case. For this, the values are presented in a comma-separated list like:
package main
import (
"fmt"
)
func main() {
ans := Check(5)
fmt.Println(ans)
}
func Check(c int) bool {
switch c {
case 1, 3, 5:
return true
}
return false
}
true
The switch statements in Go work in a top to bottom manner, which simply means that the cases that are present above will be executed first, also it is recommended that we should place the most probable values first, to save the time of computation. The first branch that is correct is executed, and then the switch statement is complete.
It is also possible that a case might not have anybody or a statement to execute.
Consider the example shown below that depicts the scenario where one of the cases might not have a single statement in it.
Example 4: Go Switch case with no statement
It is possible that the switch case does not have any statement in that case nothing will execute.
package main
import (
"fmt"
)
func main() {
ans := Check(9)
fmt.Println(ans)
}
func Check(c int) bool {
switch c {
case 1, 3, 5:
return true
case 11:
case 9:
return false
}
return false
}
false
In the above example, we noticed that case 11: doesn't have any statement to execute, and in order to achieve the same syntax in languages like C or Java, we would have to make use of the break keyword, but in Go, the switch statement doesn't require a break keyword as there is no fallthrough.
In case, if we want to have a fallthrough, we might have to explicitly put one there.
Consider the example shown below where we have been putting the fallthrough keyword in all the cases which will allow the execution control to fall from one case to another.
Example 5: Go Switch with fallthrough
By default switch case execution does not fallthrough it means only matched case executes rest of the cases skip, but if you want to execute all the cases after matching one then use fallthrough keyword.
package main
import (
"fmt"
)
func main() {
var x int = 2
switch x {
case 1:
fmt.Println("Case 1")
fallthrough
case 2:
fmt.Println("Case 2")
fallthrough
case 3:
fmt.Println("Case 3")
fallthrough
default:
fmt.Println("IDK")
}
}
Case 2
Case 3
IDK
What the fallthrough keyword does is that it transfers the control to the next case. It should also be noted that the fallthrough keyword can only be used as the final statement in a switch case.
Switch statements with condition
We can also have switch statements with conditions instead of fixed type values as the cases. The condition which first evaluates to true will be executed. It looks very much like if-else chaining and offers a more readable syntax if there are many branches.
The syntax of switch statements with conditions looks like this:
switch {
case condition1:
...
case condition2:
...
default:
...
}
Let's explore an example where we will make use of conditions in the case statement instead of having variables.
Example 6: Go switch with conditions
We can make conditional switch cases like if statements, to create conditional switch statements.
package main
import (
"fmt"
)
func main() {
var x int = 2
switch {
case x < 1:
fmt.Println("Case 1")
case x < 2:
fmt.Println("Case 2")
case x < 3:
fmt.Println("Case 3")
default:
fmt.Println("IDK")
}
}
Case 3
In the above code, we declare a variable x and give it a value of 2. We can use a switch statement without any value, which means different cases will be based on conditions. We made a total of four cases, including the default case.
The first case is for a number less than 1: case x < 1. If this case is true, then line 11 will be executed. If not, then control will be transferred directly to line 12 for the second case.
The second case is for the condition less than 2: case x < 2. If this case is true, then line 13 will be executed. If not, then control will be transferred directly to line 14 for the third case.
The third case is for the condition less than 3: case x < 3. If this case is true, then line 14 will be executed. If not, then control will be transferred directly to line 16 for the fourth case.
Switch Initialization
We can also initialize the variable inside the switch statement itself, instead of making use of a variable that was declared before.
Consider the example shown below, where we are initializing a variable inside the switch statement only.
Example: Initialization inside a switch Statement
Here, we initialized the switch variable at the same time while creating the switch statement.
package main
import (
"fmt"
)
func main() {
switch x := 2;{
case x < 1:
fmt.Println("Case 1")
case x < 2:
fmt.Println("Case 2")
case x < 3:
fmt.Println("Case 3")
default:
fmt.Println("IDK")
}
}
Case 3
Conclusion
In the above article, we learned about what a Switch statement is in Go, how to make use of it, what are the different types of these statements and we also learned how they are more flexible when compared to the switch statements that are present in languages like C or Java.