Sling Academy
Home/Golang/Using the Switch statement in Go

Using the Switch statement in Go

Last updated: November 23, 2024

The switch statement in Go is a powerful control mechanism that allows you to execute different blocks of code depending on the value of an expression. It serves as an alternative to the series of if statements with multiple conditions, providing a cleaner and more readable structure.

Basic Usage

Let's start with a basic example of the switch statement. Here, we will examine how it functions when checking a single variable against different case conditions.

package main

import (
    "fmt"
)

func main() {
    day := "Monday"

    switch day {
    case "Monday":
        fmt.Println("Start of the work week.")
    case "Friday":
        fmt.Println("End of the work week.")
    default:
        fmt.Println("Midweek.")
    }
}

This code will print "Start of the work week." because the variable day matches the "Monday" case.

Intermediate Example

We can also use multiple expressions in a single case and fallthrough to execute the next case block. Here’s how:

package main

import (
    "fmt"
)

func main() {
    number := 3

    switch number {
    case 1, 3, 5, 7:
        fmt.Println("Odd number")
    case 2, 4, 6, 8:
        fmt.Println("Even number")
    default:
        fmt.Println("Number not in range 1-8")
    }
}

In this example, since number has a value of 3, it prints "Odd number".

Advanced Usage

Besides switching based on constants, Go allows us to use expressions in switch:

package main

import (
    "fmt"
    "time"
)

func main() {
    switch t := time.Now(); { // note: switch with no expression
    case t.Hour() < 12:
        fmt.Println("Good Morning!")
    case t.Hour() < 18:
        fmt.Println("Good Afternoon!")
    default:
        fmt.Println("Good Evening!")
    }
}

Here, we switch based on the result of a boolean expression. The specific case gets executed based on the current hour. If the hour is before 12, it will print "Good Morning!", and so on.

Use switch without an Expression

It is also possible in Go to use a switch statement without an expression, which allows you to evaluate all the cases manually:

package main

import (
    "fmt"
)

func main() {
    num := 10

    switch {
    case num < 0:
        fmt.Println("Negative Number")
    case num == 0:
        fmt.Println("Zero")
    case num > 0:
        fmt.Println("Positive Number")
    }
}

This example evaluates the value of num within several conditions and prints "Positive Number" because num is greater than 0.

The flexibility and simplicity of the switch statement in Go make it preferable for many similar conditions over using multiple if-else statements.

Next Article: Ways to check type of a variable in Go

Previous Article: If, Else, and Beyond: Go's Conditional Statements

Series: Variables & Control Flow

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant