Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Switch Statement in Golang

Go language has two types of switch statements:

Syntax:

switch expression {
case x:
   // code block
case y:
   // code block
case z:
...
default:
   // code block
}
  1. Expression Switch (Single case)
  2. Type Switch (Multi case)
  1. Single-case

1. The example below uses a number to return different text

package main
import "fmt"
func main() {
    fmt.Print("Enter the No. :")
    var I int
    fmt.Scanln(&I)
    switch I {
    case 1:
        fmt.Print("The value is 10 ")
    case 2:
        fmt.Print("The value is 20 ")
    case 3:
        fmt.Print("The value is 30 ")
    case 4:
        fmt.Print("The value is 40 ")
    case 5:
    default:
        fmt.Print("Incorrect input ")
}
}

Output:

PS C:\GO_Language\Case> go run case1.go
Enter No. :4
The value is 40 
PS C:\GO_Language\Case> go run case1.go
Enter No. :2
The value is 20 
PS C:\GO_Language\Case> go run case1.go
Enter No. :1
The value is 10 
PS C:\GO_Language\Case> go run case1.go
Enter No. :6
It is not in bound

2.  The example below uses a weekday number to calculate the weekday name:

package main

import (
    "fmt"
)

func main() {
    fmt.Print("Enter Day No. :")
    var i int
    fmt.Scanln(&i)

    switch i {
    case 1:
        fmt.Println("Monday")
    case 2:
        fmt.Println("Tuesday")
    case 3:
        fmt.Println("Wednesday")
    case 4:
        fmt.Println("Thursday")
    case 5:
        fmt.Println("Friday")
    case 6:
        fmt.Println("Saturday")
    case 7:
        fmt.Println("Sunday")
    default:
        fmt.Print("It is not in bound")

    }
} 

Output :

PS C:\GO_Language\Case> go run case3.go
Enter Day No. :1
Monday
PS C:\GO_Language\Case> go run case3.go 
Enter Day No. :3
Wednesday
PS C:\GO_Language\Case> go run case3.go
Enter Day No. :5
Friday
PS C:\GO_Language\Case> go run case3.go
Enter Day No. :6
Saturday

           

2 . Multi-case

    1. The example below uses number to return different text:
      package main
      import "fmt"
      func main() {
          var value string = "five"
          switch value {
          case "one":
              fmt.Println("C#")
          case "two", "three":
              fmt.Println("Go")
          case "four", "five", "six":
              fmt.Println("java")
          }
      }
      

      Output :

      PS C:\GO_Language\Case> go run case2.go
      java
      

The post Switch Statement in Golang appeared first on Prwatech.



This post first appeared on Learn Big Data Hadoop In Bangalore, please read the originial post: here

Share the post

Switch Statement in Golang

×

Subscribe to Learn Big Data Hadoop In Bangalore

Get updates delivered right to your inbox!

Thank you for your subscription

×