Wednesday, November 14, 2018

Learn Golang tutorials - Switch case statement guide with examples

This article covers the Switch case statements with expressions and types with various syntax examples.
Learn Golang tutorials - Switch case statement guide with examples

Golang Switch case statements

Switch case is used to execute a particular code block when we have multiple code blocks based on condition. It is an alternative syntax for writing if-else block. Unlike other programming languages like Java and C+, where, the break is needed to stop its execution. Go language is automatically stopped its execution when matching case executed. Break keyword is not required.

There are two types of Switch types in Go Programming language.
  • Expression Switch - In this case, Switch expression are compared with case expressions.
  • Type Switch -Switch expressions types are compared with case expressions.

Expression Switch 

expression switch is used to compare expression with a value of case expressions.
Here is a syntax for switch case
switch (variable|boolean-expression|Integer type){
case boolean-expression | integer type
     Block of code contains statements
case boolean-expression | integer type
     Block of code contains statements
default: // default  case and it is optional
   Block of code contains statements
}
Following are the keynotes of expression switch
  • Switch executes from top to bottom, Stop its execution when a matching case occurs
  • It contains any number of case statements with each case statements contains expression and a colon.
  • the default case is optional. This will be executed when the matching case is not executed. This placed last case and break is not required 
  • Switch expression and case expression must be evaluated to the same type, Otherwise, it gives a compilation error. For example, Switch evaluates to float and case evaluates to float only. 
  • curly braces for case body is optional. 
  • if there are many matched cases, first matched cases are executed.

Example

Here is a basic example of switch case statements
In the below example, Number is declared with value 1. In the switch, number compares with the value of number against all case statements. Here cases are evaluated from top to bottom. Matched first executes its code block, In this case, 1 is matched, 1 matched is displayed to console. switch expression can be enclosed with parenthesis and without parenthesis - both switch number or switch (number) are allowed and valid code.
package main

import "fmt"

func main() {
 number := 1
 switch number {
 case 1:
  fmt.Println("1 matched")
 case 2:
  fmt.Println("2 matched")
 case 3:
  fmt.Println("3 matched")
 case 4:
  fmt.Println("4 matched")
 default:
  fmt.Println("default matched")
 }
}
Output is
1 matched
Following is various examples of the switch case

The duplicate case with same values are not allowed 

In the below code, the duplicate case is declared with the same values - case 3 is declared two times. The compiler gives compilation error - duplicate case 3 in switch previous case at
package main

import "fmt"

func main() {
 number := 1
 switch number {
 case 1:
  fmt.Println("1 matched")
 case 2:
  fmt.Println("2 matched")
 case 3:
  fmt.Println("3 matched")
 case 3:// duplciate case is declared here - Compilation error
  fmt.Println("3 matched")
 case 4:
  fmt.Println("4 matched")
 default:
  fmt.Println("default matched")
 }
}

Default case when the matched case is not declared

what will happens when the number is given as 10? to the same example. the matching case for the number is not defined in code, hence default case will be executed and printed default matched text is printed to the console output

package main

import "fmt"

func main() {
 number := 11
 switch number {
 case 1:
  fmt.Println("1 matched")
 case 2:
  fmt.Println("2 matched")
 case 3:
  fmt.Println("3 matched")
 case 4:
  fmt.Println("4 matched")
 default:
  fmt.Println("default matched")
 }
}
of the above program is
default matched
The default case is an optional case. It is advisable to be last case statement but there is no effect on the way of switch case functionality

Switch with No expression or Condition 

The switch can also be declared without expression or condition. When no expression is used, It treats switch case as a true value. switch with no expression or condition or value always equals to switch true. case expression always should be expression or condition
package main

import "fmt"

func main() {
 number := 11
 switch {
 case number > 10:
  fmt.Println("Number is greater than 10")
 case number > 20:
  fmt.Println("Number is greater than 20")
 case number > 30:
  fmt.Println("Number is greater than 30")
 default:
  fmt.Println("default matched")
 }
}
and output of the program code is
number is greater than 10
when no expressions in the switch case, case expression must be non-constants
package main

import "fmt"

func main() {
 number := 11
 switch {
 case 1:
  fmt.Println("1 matched")
 case 2:
  fmt.Println("2 matched")
 case 3:
  fmt.Println("3 matched")
 case 4:
  fmt.Println("4 matched")
 default:
  fmt.Println("default matched")
 }
}
the above code is not compiled The reason is switch without expression code should have case non-constants The compilation error is invalid case 1 in a switch (mismatched types int and bool) Complete error for the command is go run filename
.\First.go:8:2: invalid case 1 in switch (mismatched types int and bool)
.\First.go:10:2: invalid case 2 in switch (mismatched types int and bool)
.\First.go:12:2: invalid case 3 in switch (mismatched types int and bool)
.\First.go:14:2: invalid case 4 in switch (mismatched types int and bool)

Switch case contains multiple expressions or conditions 

Case contains multiple expressions separated by comma symbol


package main

import "fmt"

func main() {
 weekday := "tuesday"
 switch weekday {
 case "monday", "tuesday", "wednesday", "thursday", "friday":
  fmt.Println("Working Day")
 default:
  fmt.Println("Not working day: weekend")
 }
}
The output of the above program is
Working Day
the above code, Code cheks weekday is working day or not. the case is defined with multiple strings which are declared as working days.

fallthrough keyword in the case body 

Normally when the matched case is found with switch case, the code inside matched case executes and control exit from switch case. fallthrough statement is special functionality used to jump the control from next immediate available case fallthrough is a keyword in golang, hence it will not be used as variable or function names.
package main

import "fmt"

func main() {
 number := 1
 switch number {
 case 1:
  fmt.Println("1 matched")
  fallthrough
 case 2:
  fmt.Println("2 matched")
  fallthrough
 case 3:
  fmt.Println("3 matched")
 case 4:
  fmt.Println("4 matched")
 default:
  fmt.Println("default matched")
 }
}
The output of the above program is
1 matched
2 matched
3 matched
without fallthrough statement, The output is
1 matched
In the above code, Control comes to the matched case, case 1 is matched, fallthrough statement exists, Control transfer to the first line of code of next case 2 statement. fallthrough statement is the last statement inside the code of case statement. if you declare fallthrough as not line of code, It gives compilation error the following code gives fallthrough statement out of place
func main() {
 number := 1
 switch number {
 case 1:
  fallthrough // not allowed as first or middle - compilation error
  fmt.Println("1 matched")
 case 2:
  fmt.Println("2 matched")
  fallthrough
 case 3:
  fmt.Println("3 matched")
 case 4:
  fmt.Println("4 matched")
 default:
  fmt.Println("default matched")
 }

switch case floating values

Switch and case expression can also be declared with floating values and it is valid code. Other languages are not supported to be used in switch case expressions. Golang has no issues with it. The below program contains floating numbers, matched case with floating values are evaluated. In this case, 6.5 matched is printed to the console.
func main() {
 number := 6.5
 switch number {
 case 5.5:
  fmt.Println("5.5 matched")
 case 6.5:
  fmt.Println("6.5 matched")
 default:
  fmt.Println("default matched")
 }
}
and output of the above program is
6.5 matched 

switch case String literals 

allowed Expression can also be string literals. String literals are a group of characters enclosed in double quotes. It checks the exact match of string literals. In the below code, Case contains String literals, Switch expression contain string variable, the Matched case is evaluated, and output is TWO matched
func main() {
 number := "TWO"
 switch number {
 case "ONE":
  fmt.Println("ONE matched")
 case "TWO":
  fmt.Println("TWO matched")
 default:
  fmt.Println("default matched")
 }
}
The output of the above program is
TWO matched

Break statement to exit from the loop

break statement can also be used in switch cases. It is used to exit from the inner loop inside the switch. When you are using for loop with switch case, break keyword will be used. Here is an example without break statement for loop iterates with 3 values, Inside the loop, Switch is declared, and matched cases values are printed.


func main() {
 var numbArray = [3]int{1, 2, 5}
 for _, numb := range numbArray {
  switch numb {
  case 1:
   fmt.Println("1 matched")
  case 2:
   fmt.Println("2 matched")
   break
  case 0:
   fmt.Println("0 matched")
  }
 }
}
Output is
1 matched
2 matched
Now we will rewrite the code with break and named labels in switch case statements In the below loop code, for the first matched case, break label is used, It exists from the named label and output only 1 matched case.
func main() {
 var numbArray = [3]int{1, 2, 5}
MyLoopName:
 for _, numb := range numbArray {
  switch numb {
  case 1:
   fmt.Println("1 matched")
   break MyLoopName
  case 2:
   fmt.Println("2 matched")
   break
  case 0:
   fmt.Println("0 matched")
  }
 }
}
Output is
1 matched

Functions can be used as Expression in switch and case 

the expression can also be a function named calls and valid in go language Following is an example for functions in switch expressions. In the below example, the Simple function is declared, It just returns the passed parameter no value is processed. This is being used in Switch expression as well as case expression.
func myfunction(parameter string) string {
 return parameter
}
func main() {
 switch myfunction("mon") {
 case myfunction("mon"), myfunction("tue"), myfunction("wed"), myfunction("thu"), myfunction("fri"):
  fmt.Println("working day")
 case myfunction("sat"), myfunction("sun"):
  fmt.Println("Not working day: weekend")
 }
}
Output is
working day

Type Switch

Type switch is mostly used in interfaces Type switch is do multiple type checking and evaluates first matched type case. These are mostly used to type assertions Difference between the expression switch and type switch, the Normal switch is compared values with case values. Type switch compares types not values with case types.
Here is a syntax for type switch
switch variable.(type){
case type:
  Code block statements
case type:
  code block statements
default:
  code block statements
}
variable.(type) represents type assertion that contains specific type as "type" Following are key points of the type switch expressions
  • You can define any number of case statements
  • The expression defined in this type always of interface type variable
  • Like a normal switch expression, Default is also optional and last declared, the break is not required.
  • Switch type and case type must be of the same type or follows is-a principal.
  • When switch type and case type is matched, matched case code body is executed, exit from the switch code, Break is not required 

switch type assertion interface example

 In the below example, interface() is an empty interface type that can accept any type of value.
package main

import "fmt"

func main() {
 var interfaceDemo interface{} = 45

 switch interfaceDemo.(type) {
 case string:
  fmt.Println("string type matched")
 case int:
  fmt.Println("int type matched")
 default:
  fmt.Println("default type matched")

 }
}
The output is
int type matched

a type switch struct example 

Type switch case can be used with struct data types. struct types contain custom type which contains multiple types.
package main

import "fmt"

func main() {
 type Employee struct {
  ID   int
  Name string
 }
 emp := Employee{1, "Kiran"}
 var empInterface interface{}
 empInterface = emp
 switch empInterface.(type) {
 case Employee:
  fmt.Println("Employee type matched")
 case string:
  fmt.Println("String type matched")
 default:
  fmt.Println("default type matched")
 }
}
output
Employee type matched
Please share your valuable comments and feedback:) and share it on facebook

Related article


EmoticonEmoticon