Skip to main content
Published on

Switch in Go

Share:

Introduction

The switch is a powerful tool in Go, allowing programmers to make decisions based on multiple cases. Unlike conditionals with if and else, switch is often more readable, especially when dealing with many conditions.

Switch Fundamentals

  1. Equality Check: The switch compares the given expression against the values of each case.
  2. Single Execution: Unlike other languages, in Go, once a case matches, the program exits the switch block. No explicit "break" is needed.
  3. Default Clause: If no case matches, the code under default will be executed. However, default is optional.

Basic Switch

day := "thursday"

switch day {
case "monday":
	fmt.Println("Today is Monday.")
case "tuesday":
	fmt.Println("Today is Tuesday.")
default:
	fmt.Println("It is neither Monday nor Tuesday.")
}

Switch with Multiple Conditions in a Case

You can combine multiple possible values in a single case:

letter := 'B'

switch letter {
case 'A', 'E', 'I', 'O', 'U':
	fmt.Println("Vowel")
default:
	fmt.Println("Consonant")
}

Switch with Initialiser

Just like the if statement, switch can also have an initialisation:

switch num := 5; num {
case 1, 3, 5, 7, 9:
	fmt.Println("Odd number")
default:
	fmt.Println("Even number")
}

Type Switch

Go also supports a type-based switch, which is useful when working with interfaces:

var x interface{} = "text"

switch x.(type) {
case int:
	fmt.Println("x is an integer")
case string:
	fmt.Println("x is a string")
default:
	fmt.Println("Unknown type")
}

Conclusion

The switch statement in Go offers a clean and efficient way to handle multiple conditions. Whether checking values or types, switch makes code more organised and readable.

Happy coding!