How to use Switch Statement in Golang?

Last updated on May 12, 2023

Golang has switch statements as other programming languages have, for example, JavaScript, PHP Java, etc.

The switch statement runs a specific code block based on the match case. It takes an expression that has to match a series of cases. It runs the code block when the case matches the expression.

Syntax

switch expression{
case value1:
   // if expression matches with value1 then this block will run
case value2:
   // if expression matches with value2 then this block will run
case value3:
  // if expression matches with value3 then this block will run

default:
   // if expression doesn't match with any case or value then default will run
}

The switch statement takes an expression and matches it with all defined cases. If any case’s value matches the expression the switch statement runs that code block. In case of failure, the switch statement runs the default statement.

The Golang switch statement doesn’t need a break keyword after each case which is because Golang terminates the switch statement after matching the case. While in some languages like PHP and JavaScript, it is required.

Example

Let’s suppose we have a variable that stores integers that can be 1 to 5 and we need to run a specific code block based on the expression’s value.

  number := 3

  switch number {
  case 1:
    fmt.Println("Matched with case 1")
  case 2:
    fmt.Println("Matched with case 2")
  case 3:
    fmt.Println("Matched with case 3")
  case 4:
    fmt.Println("Matched with case 4")
  case 5:
    fmt.Println("Matched with case 5")
  default:
   fmt.Println("Case couldn't match, it is default case.")
  }

// Output: Matched with case 3

In this example, the number variable stores an integer value that is 3. The switch statement takes the variable and matches it with all the cases. Since the variable has value 3 so it matches with case 3. That’s why it runs the code block which is specified in the case 3.

Switch statement runs the default case when all the cases fail to match with the expression value.


Written by
I am a skilled full-stack developer with extensive experience in creating and deploying large and small-scale applications. My expertise spans front-end and back-end technologies, along with database management and server-side programming.

Share on:

Related Posts

Tags: Golang,