Saturday 28 August 2021

What is Go Language switch?

 The Go switch statement executes one statement from multiple conditions. It is similar to if-else-if chain statement.

Syntax:

  1. switch  var1 {  
  2. case val1:  
  3. .....  
  4. case val2  
  5. .....  
  6. default:  
  7. .....  
  8. }  

The switch statement in Go is more flexible. In the above syntax, var1 is a variable which can be of any type, and val1, val2, ... are possible values of var1.

In switch statement, more than one values can be tested in a case, the values are presented in a comma separated list

like: case val1, val2, val3:

If any case is matched, the corresponding case statement is executed. Here, the break keyword is implicit. So automatic fall-through is not the default behavior in Go switch statement.

For fall-through in Go switch statement, use the keyword "fallthrough" at the end of the branch.

Go Switch Example:

  1. package main  
  2. import "fmt"  
  3. func main() {  
  4.    fmt.Print("Enter Number: ")  
  5.   var input int  
  6.   fmt.Scanln(&input)  
  7.    switch (input) {  
  8.   case 10:  
  9.       fmt.Print("the value is 10")  
  10.     case 20:  
  11.       fmt.Print("the value is 20")  
  12.     case 30:  
  13.       fmt.Print("the value is 30")  
  14.     case 40:  
  15.       fmt.Print("the value is 40")  
  16.     default:  
  17.       fmt.Print(" It is not 10,20,30,40 ")  
  18.    }  
  19. }  

Output:

Enter Number: 20
the value is 20

or

Output:

Enter Number: 35
 It is not 10,20,30,40

Go switch fallthrough example

  1. import "fmt"  
  2. func main() {  
  3.    k := 30  
  4.    switch k {  
  5.    case 10:  
  6.       fmt.Println("was <= 10"); fallthrough;  
  7.    case 20:  
  8.       fmt.Println("was <= 20"); fallthrough;  
  9.    case 30:  
  10.       fmt.Println("was <= 30"); fallthrough;  
  11.    case 40:  
  12.       fmt.Println("was <= 40"); fallthrough;  
  13.    case 50:  
  14.       fmt.Println("was <= 50"); fallthrough;  
  15.    case 60:  
  16.       fmt.Println("was <= 60"); fallthrough;  
  17.    default:  
  18.       fmt.Println("default case")  
  19.    }  
  20. }  

Output:

was <= 30
was <= 40
was <= 50
was <= 60
default case


No comments:

Post a Comment