Introduction
A switch statement helps you choose between many options easily. It makes your code cleaner than many if-else checks.
A switch statement helps you choose between many options easily. It makes your code cleaner than many if-else checks.
switch variable { case value1: // code to run if variable == value1 case value2: // code to run if variable == value2 default: // code to run if no case matches }
The default case runs if no other case matches.
You don't need to write break in Go; it stops automatically after a case.
switch day { case "Monday": fmt.Println("Start of the week") case "Friday": fmt.Println("Almost weekend") default: fmt.Println("Just another day") }
switch { case age < 13: fmt.Println("Child") case age < 20: fmt.Println("Teenager") default: fmt.Println("Adult") }
This program checks the fruit variable and prints a message based on its value.
package main import "fmt" func main() { fruit := "apple" switch fruit { case "apple": fmt.Println("This is an apple.") case "banana": fmt.Println("This is a banana.") default: fmt.Println("Unknown fruit.") } }
Go's switch stops automatically after a matching case; no need for breaks.
You can use switch without a variable to check conditions directly.
Use default to handle unexpected cases.
Switch helps pick one action from many choices.
It makes code easier to read than many if-else statements.
Go switch automatically stops after a case runs.
switch statement do in Go?switch variable { case value: ... default: ... } without parentheses.package main
import "fmt"
func main() {
x := 2
switch x {
case 1:
fmt.Println("One")
case 2:
fmt.Println("Two")
case 3:
fmt.Println("Three")
default:
fmt.Println("Other")
}
}x is 2.2 matches and prints "Two".package main
import "fmt"
func main() {
x := 3
switch x {
case 1
fmt.Println("One")
case 2:
fmt.Println("Two")
default:
fmt.Println("Other")
}
}case 1 misses the colon.case 6, 7: groups Saturday and Sunday together.Pass the test and this pattern moves unknown