Module: Control Flow

Switch

Go Programming: Control Flow - Switch

The switch statement in Go is a powerful control flow mechanism that allows you to execute different blocks of code based on the value of an expression. It's a more structured alternative to a series of if-else if-else statements, especially when dealing with multiple possible values.

Basic Syntax:

switch expression {
case value1:
    // Code to execute if expression == value1
case value2:
    // Code to execute if expression == value2
case value3:
    // Code to execute if expression == value3
default:
    // Code to execute if expression doesn't match any of the cases
}

Key Features and Rules:

  • Expression Evaluation: The expression is evaluated once.
  • Case Matching: Each case is compared against the result of the expression. If a match is found, the corresponding code block is executed.
  • Fallthrough (Optional): Unlike some other languages, Go's switch does not automatically fall through to the next case. If you want to execute multiple cases sequentially, you must explicitly use the fallthrough keyword.
  • No Conditionals in Cases: Cases cannot contain conditions (e.g., case x > 5:). You must use if-else if-else for conditional logic within the cases.
  • default Case: The default case is optional. If no other case matches, the default case is executed. If there's no default case and no other case matches, nothing happens.
  • Multiple Values in a Case: You can specify multiple values in a single case separated by commas. The expression will match if it equals any of the values in the case.
  • Type Switches: switch can also be used to determine the type of a variable (more on this later).

Example 1: Simple Switch

package main

import "fmt"

func main() {
	day := "Monday"

	switch day {
	case "Monday":
		fmt.Println("Start of the work week")
	case "Friday":
		fmt.Println("Almost weekend!")
	case "Saturday", "Sunday": // Multiple values in a case
		fmt.Println("Weekend!")
	default:
		fmt.Println("Not a valid day")
	}
}

Output:

Start of the work week

Example 2: Using fallthrough

package main

import "fmt"

func main() {
	number := 2

	switch number {
	case 1:
		fmt.Println("One")
		fallthrough // Execute the next case
	case 2:
		fmt.Println("Two")
		fallthrough // Execute the next case
	case 3:
		fmt.Println("Three")
	default:
		fmt.Println("Other")
	}
}

Output:

One
Two
Three

Example 3: Switch without an Expression

You can use switch as a replacement for a series of if-else if-else statements by omitting the expression. In this case, each case must include a boolean condition.

package main

import "fmt"

func main() {
	score := 85

	switch {
	case score >= 90:
		fmt.Println("Grade: A")
	case score >= 80:
		fmt.Println("Grade: B")
	case score >= 70:
		fmt.Println("Grade: C")
	default:
		fmt.Println("Grade: D")
	}
}

Output:

Grade: B

Example 4: Type Switch

A type switch allows you to determine the type of a variable and execute different code based on its type.

package main

import "fmt"

func main() {
	var i interface{} = "Hello"

	switch v := i.(type) { // Type assertion and variable assignment
	case int:
		fmt.Println("Integer:", v)
	case string:
		fmt.Println("String:", v)
	case bool:
		fmt.Println("Boolean:", v)
	default:
		fmt.Println("Unknown type")
	}

	i = 10
	switch v := i.(type) {
	case int:
		fmt.Println("Integer:", v)
	case string:
		fmt.Println("String:", v)
	case bool:
		fmt.Println("Boolean:", v)
	default:
		fmt.Println("Unknown type")
	}
}

Output:

String: Hello
Integer: 10

Explanation of Type Switch:

  • i.(type): This is a type assertion. It checks the underlying type of the interface variable i.
  • v := i.(type): This not only determines the type but also assigns the value of i to a new variable v of the determined type. This allows you to work with the value directly within the case.

When to Use switch:

  • When you have multiple possible values for an expression and want to execute different code based on those values.
  • When you need to determine the type of a variable and execute different code based on its type (type switch).
  • To improve code readability and maintainability compared to a long chain of if-else if-else statements.

In summary, the switch statement is a versatile and powerful control flow tool in Go that can help you write cleaner, more readable, and more maintainable code.