Go Switch

Go language Switch statement is used to evaluate an expression and run a case that matches with this value.

In this tutorial, we will learn the syntax of Switch statement and its usage with examples.

There are two variations in the syntax of Switch statement. We shall go through these two variations.

Switch with Expression

The syntax of Switch statement with expression right after the switch keyword is

</>
Copy
switch expression {
	case value1:
		statement(s)
	case value2:
		statement(s)
	default:
		statement(s)	
}

where switch, case and default are the keywords. expression should evaluate to a value of type as that of the case values.

There could be multiple case blocks. The default block is optional. If no case value matches the expression‘s value, the default block is executed.

Example

In the following example, we have taken a simple expression of a variable today. Based on its value, we are printing what day of the week it is using switch statement.

example.go

</>
Copy
package main

import "fmt"

func main() {
	var today int = 2

	switch today {
	case 1:
		fmt.Printf("Today is Monday")
	case 2:
		fmt.Printf("Today is Tuesday")
	case 3:
		fmt.Printf("Today is Wednesday")
	case 4:
		fmt.Printf("Today is Thursday")
	case 5:
		fmt.Printf("Today is Friday")
	case 6:
		fmt.Printf("Today is Saturday")
	case 7:
		fmt.Printf("Today is Sunday")
	default:
		fmt.Printf("Value for today is invalid.")
	}
}

Output

Today is Tuesday

Switch without Expression

You can also write switch statement without expression mentioned right after the switch keyword.

The syntax of switch statement without expression is

</>
Copy
switch {
	case expression1==value1:
		statement(s)
	case expression2==value2:
		statement(s)
	default:
		statement(s)	
}

where switch, case and default are the keywords. The expression can vary from case to case.

Example

In the following example, we have taken the expression to case blocks. We have used the same expression for all cases, but we can use a different expression for any of the case block(s).

example.go

</>
Copy
package main

import "fmt"

func main() {
	var today int = 4
	
	switch {
		case today==1:
			fmt.Printf("Today is Monday")
		case today==2:
			fmt.Printf("Today is Tuesday")
		case today==3:
			fmt.Printf("Today is Wednesday")
		case today==4:
			fmt.Printf("Today is Thursday")
		case today==5:
			fmt.Printf("Today is Friday")
		case today==6:
			fmt.Printf("Today is Saturday")
		case today==7:
			fmt.Printf("Today is Sunday")
		default:
			fmt.Printf("Value for today is invalid.")
	}
}

Output

Today is Thursday

Conclusion

In this Golang Tutorial, we learned about Switch statement in Go programming language, its variations, and how to use them with the help of example programs.