0
0
Goprogramming~5 mins

Switch statement in Go

Choose your learning style9 modes available
Introduction

A switch statement helps you choose between many options easily. It makes your code cleaner than many if-else checks.

When you want to run different code based on a variable's value.
When you have many conditions to check against one value.
When you want clearer code instead of many if-else statements.
Syntax
Go
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.

Examples
This checks the day and prints a message for Monday, Friday, or any other day.
Go
switch day {
case "Monday":
    fmt.Println("Start of the week")
case "Friday":
    fmt.Println("Almost weekend")
default:
    fmt.Println("Just another day")
}
This switch uses conditions without a variable to check age ranges.
Go
switch {
case age < 13:
    fmt.Println("Child")
case age < 20:
    fmt.Println("Teenager")
default:
    fmt.Println("Adult")
}
Sample Program

This program checks the fruit variable and prints a message based on its value.

Go
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.")
    }
}
OutputSuccess
Important Notes

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.

Summary

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.