๐ŸŽ“ A1Learner
๐Ÿ”
0 of 38 lessons completed

Go Switch

A switch statement is code that matches one value against a list of cases. The case with the matching value runs its statements.

Matching one case

The value 3 matches case 3. That case prints its day name.

package main

import "fmt"

func main() {
	day := 3
	switch day {
	case 1:
		fmt.Println("Monday")
	case 2:
		fmt.Println("Tuesday")
	case 3:
		fmt.Println("Wednesday")
	case 4:
		fmt.Println("Thursday")
	}
}

Sharing one case

Cases 6 and 7 share one case line. The value 6 matches that shared case.

package main

import "fmt"

func main() {
	day := 6
	switch day {
	case 6, 7:
		fmt.Println("Weekend")
	default:
		fmt.Println("Weekday")
	}
}

Falling through

The fallthrough statement carries the run into the next case. Both cases print a line.

package main

import "fmt"

func main() {
	n := 2
	switch n {
	case 2:
		fmt.Println("two")
		fallthrough
	case 3:
		fmt.Println("three")
	case 4:
		fmt.Println("four")
	}
}

A switch with no value

This switch names no value after the switch word. Each case holds a full condition instead.

package main

import "fmt"

func main() {
	score := 85
	switch {
	case score >= 90:
		fmt.Println("Band: A")
	case score >= 80:
		fmt.Println("Band: B")
	default:
		fmt.Println("Band: C")
	}
}

Example

package main

import "fmt"

func main() {
	grade := "B"
	switch grade {
	case "A":
		fmt.Println("Excellent")
	case "B":
		fmt.Println("Good")
	case "C":
		fmt.Println("Fair")
	default:
		fmt.Println("Try again")
	}
}

Key points

  • Each case names a value to match against the switch value.
  • A case can list more than one value, split by commas.
  • The default case runs when no case matches.
  • The fallthrough statement runs the next case as well.
  • A switch with no value after switch tests conditions in its cases.

In this example, grade holds the string B. The switch tests it against each case in order. Case B is the match, so its line prints. The printed line is "Good".

Note

A matched case ends on its own and does not run the next case.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Go Playground

Exercise

What does the fallthrough statement do?