Switch-Case Statements

1-minute read
Table of Contents

Switch statements are used as an alternative to if-else statements with many branches in which each branch checks to see if a value or expression matches a target:

package main

import "fmt"

func main() {
	var choice int

	fmt.Println("Please enter a number: ")
	fmt.Scanln(&choice)
	switch choice {
	case 1:
		fmt.Println("You chose option 1")
	case 2, 3:
		fmt.Println("You chose either 2 or 3")
	case 4:
		fmt.Println("You chose option 4")
	default:
		fmt.Println("That is not a valid option")
	}
}
switch.go
Copy

Notice how we can have many values as is listed in case 2, 3. If the value of choice does not match any of the cases, the default will run. In this case, the user is told that the choice is not a valid option.

A note on Scanln

The Scanln function in the fmt package is used to accept input from the user and store that input in the choice variable. The notation &choice is used because Scanln needs to access the memory address of choice in order to change its value. The memory address is represented in our code by &choice.

Support us via BuyMeACoffee