Easy Tutorial
❮ Go If Else Statement Go If Statement ❯

Go Language Switch Statement

Go Language Conditional Statements

The switch statement is used to perform different actions based on different conditions. Each case branch is unique and is tested sequentially from top to bottom until a match is found.

The switch statement executes from top to bottom until a match is found, and no break is needed after the match.

By default, the switch statement includes a break at the end of each case. Once a match is successful, it will not execute other cases. If we need to execute the subsequent cases, we can use fallthrough.

Syntax

The syntax for the switch statement in the Go programming language is as follows:

switch var1 {
    case val1:
        ...
    case val2:
        ...
    default:
        ...
}

The variable var1 can be of any type, and val1 and val2 can be any values of the same type. The type is not limited to constants or integers but must be the same type; or expressions that result in the same type.

You can test multiple possible matching values using commas to separate them, for example: case val1, val2, val3.

Example

package main

import "fmt"

func main() {
   /* Define local variables */
   var grade string = "B"
   var marks int = 90

   switch marks {
      case 90: grade = "A"
      case 80: grade = "B"
      case 50,60,70 : grade = "C"
      default: grade = "D"  
   }

   switch {
      case grade == "A" :
         fmt.Printf("Excellent!\n" )    
      case grade == "B", grade == "C" :
         fmt.Printf("Well done\n" )   
      case grade == "D" :
         fmt.Printf("Pass\n" )   
      case grade == "F":
         fmt.Printf("Fail\n" )
      default:
         fmt.Printf("Poor\n" );
   }
   fmt.Printf("Your grade is %s\n", grade );   
}

The above code execution result is:

Excellent!
Your grade is A

Type Switch

The switch statement can also be used for type-switch to determine the type of variable actually stored in an interface variable.

The syntax for Type Switch is as follows:

switch x.(type){
    case type:
       statement(s);      
    case type:
       statement(s); 
    /* You can define any number of cases */
    default: /* Optional */
       statement(s);
}

Example

package main

import "fmt"

func main() {
   var x interface{}

   switch i := x.(type) {
      case nil:   
         fmt.Printf("Type of x :%T",i)                 
      case int:   
         fmt.Printf("x is int")                         
      case float64:
         fmt.Printf("x is float64")          
      case func(int) float64:
         fmt.Printf("x is func(int)")                       
      case bool, string:
         fmt.Printf("x is bool or string")   
      default:
         fmt.Printf("Unknown type")   
   }   
}

The above code execution result is:

Type of x :<nil>

Fallthrough

The fallthrough keyword is used to force the execution flow to fall through the successive case block. Using fallthrough will force the execution of the subsequent case statements; fallthrough does not check if the next case's expression result is true.

Example

package main

import "fmt"

func main() {

    switch {
    case false:
            fmt.Println("1、case condition is false")
            fallthrough
    case true:
            fmt.Println("2、case condition is true")
            fallthrough
    case false:
            fmt.Println("3、case condition is false")
            fallthrough
    case true:
            fmt.Println("4、case condition is true")
    case false:
            fmt.Println("5、case condition is false")
            fallthrough
    default:
            fmt.Println("6、default case")
    }
}

The above code execution results in:

2、case condition is true
3、case condition is false
4、case condition is true

From the output of the above code, it can be seen that the switch starts executing from the first case whose condition expression is true. If a case has fallthrough, the program will continue to execute the next case without checking if the next case's expression is true.

Go Language Decision Making

❮ Go If Else Statement Go If Statement ❯