Friday, 3 May 2019

Go Language: switch statement


Syntax
switch expression {

         case caseStatement1 :
                  statements

         case caseStatement2 :
                  statements

         …..
…..
default :
         statements
         break
}


HelloWorld.go
package main

import "fmt"

func main() {

 a := 10

 switch a {
  case 10 :
   fmt.Println("Value of a is 10")

  case 20 :
   fmt.Println("Value of a is 20")
 }
}

Output
Value of a is 10

If the value in switch statement is not matched to anything, then default block gets executed.


HelloWorld.go
package main

import "fmt"

func main() {

 a := 100

 switch a {
  case 10 :
   fmt.Println("Value of a is 10")

  case 20 :
   fmt.Println("Value of a is 20")

  default :
   fmt.Println("Default block is executed")
 }
}

Output
Default block is executed

Just like ‘if’ statement in Go, you can add initialization in switch statement itself.

switch a :=10; a {

}


HelloWorld.go
package main

import "fmt"

func main() {

 switch a :=10; a {
  case 10 :
   fmt.Println("Value of a is 10")

  case 20 :
   fmt.Println("Value of a is 20")

  default :
   fmt.Println("Default block is executed")
 }
}

Output
Value of a is 10

You can even omit the expression after switch statement.


HelloWorld.go
package main

import "fmt"

func main() {

 a :=10

 switch {
  case a == 10 :
   fmt.Println("Value of a is 10")

  case a > 5 :
   fmt.Println("Value of a is > 5")

  case a < 5 :
   fmt.Println("Value of a is < 5")

  default :
   fmt.Println("Default block is executed")
 }
}

Output
Value of a is 10


As you see the output, even though both the cases, a == 10, a > 5 are 
evaluating to true, only first matching statement code gets executed.



Previous                                                 Next                                                 Home

No comments:

Post a Comment