0
0
Goprogramming~5 mins

Switch expression behavior in Go

Choose your learning style9 modes available
Introduction

A switch expression helps you choose one action from many options easily. It makes your code cleaner and easier to read than many if-else statements.

When you want to run different code based on the value of a variable.
When you have many possible cases to check and want clear code.
When you want to replace multiple if-else statements with simpler syntax.
When you want to handle different types or values in a neat way.
Syntax
Go
switch variable {
case value1:
    // code for value1
case value2:
    // code for value2
default:
    // code if no case matches
}

The switch keyword starts the switch expression.

Each case checks for a value to match the variable.

Examples
This example prints a message depending on the day string.
Go
switch day {
case "Monday":
    fmt.Println("Start of the week")
case "Friday":
    fmt.Println("Almost weekend")
default:
    fmt.Println("Just another day")
}
You can group multiple values in one case separated by commas.
Go
switch number {
case 1, 3, 5:
    fmt.Println("Odd number")
case 2, 4, 6:
    fmt.Println("Even number")
default:
    fmt.Println("Unknown number")
}
Switch can be used without a variable to check conditions directly.
Go
switch {
case x < 0:
    fmt.Println("Negative")
case x == 0:
    fmt.Println("Zero")
case x > 0:
    fmt.Println("Positive")
}
Sample Program

This program uses a switch expression without a variable to check score ranges and print the grade.

Go
package main

import "fmt"

func main() {
    score := 85
    switch {
    case score >= 90:
        fmt.Println("Grade: A")
    case score >= 80:
        fmt.Println("Grade: B")
    case score >= 70:
        fmt.Println("Grade: C")
    default:
        fmt.Println("Grade: F")
    }
}
OutputSuccess
Important Notes

Switch cases stop checking after the first match, so no need for break statements.

You can use expressions in cases, not just fixed values.

The default case runs if no other case matches.

Summary

Switch expressions let you pick one action from many choices clearly.

They can check values or conditions directly.

Switch stops after the first matching case, making code simple and clean.