Switch with Expressions
Part of the Fundamentals section of Coddy's GO journey — lesson 40 of 109.
Let's learn about switch expressions in Go, which allow us to evaluate a value directly in the switch statement.
First, let's see how to use a switch statement with an expression to check if a number is positive, negative, or zero:
num := -5
switch {
case num > 0:
fmt.Println("Positive number")
case num < 0:
fmt.Println("Negative number")
default:
fmt.Println("Zero")
}After executing this code, the program will show on the screen:
Negative numberNotice that we're using switch { with no value after it. This means Go will evaluate each case expression as a boolean condition. Since num is -5, the second case num < 0 evaluates to true, so "Negative number" is printed.
We can also initialize a variable right in the switch statement. Let's see how that works:
switch num := -5; {
case num > 0:
fmt.Println("Positive number")
case num < 0:
fmt.Println("Negative number")
default:
fmt.Println("Zero")
}After executing this code, we get the same result:
Negative numberIn this example, we declared and initialized num directly in the switch statement. The semicolon separates the initialization from the switch expression (which is empty here). This makes our code more compact while keeping the same functionality.
Challenge
Beginnerswitch expression in Go. You need to complete the code to determine the description of a day based on its name using a switch statement.A variable
dayName is already defined with the value "Wednesday". Your task is to use a switch expression to set the description variable to:-
"Start of the week" for Monday-
"Midweek" for Wednesday-
"Almost weekend" for Friday-
"Weekend" for Saturday or Sunday-
"Regular day" for any other dayCheat sheet
Switch expressions in Go allow you to evaluate conditions directly in the switch statement.
Use switch { with no value to evaluate boolean expressions in each case:
num := -5
switch {
case num > 0:
fmt.Println("Positive number")
case num < 0:
fmt.Println("Negative number")
default:
fmt.Println("Zero")
}You can initialize a variable directly in the switch statement using a semicolon to separate initialization from the switch expression:
switch num := -5; {
case num > 0:
fmt.Println("Positive number")
case num < 0:
fmt.Println("Negative number")
default:
fmt.Println("Zero")
}Try it yourself
package main
import "fmt"
func main() {
// The day name is already defined
dayName := "Wednesday"
// Variable to store the description
var description string
// TODO: Write a switch statement that sets the description based on dayName
// For Monday: "Start of the week"
// For Wednesday: "Midweek"
// For Friday: "Almost weekend"
// For Saturday or Sunday: "Weekend"
// For any other day: "Regular day"
// Print the result
fmt.Printf("%s is %s\n", dayName, description)
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Comparison & Logical Operators
Comparison Operators - Part 1Comparison Operators - Part 2Logical AND OperatorLogical OR OperatorLogical NOT OperatorOperator Precedence BasicsRecap - Making Comparisons7Control Flow: Loops
What The `for` Loop ExplainedFor Loop - BasicFor Loop - Condition OnlyThe `break` KeywordThe `continue` KeywordNested LoopsRecap - Repeating Actions2Variables and Basic Data Types
What is a variableType Inference with `:=`Integers (int)Floating-Point NumbersBooleansStringsZero ValuesConstantsNaming ConventionsRecap - Variables and Types5Basic Input/Output
Formatted OutputFormat VerbsPrinting TypesGetting Basic User InputRecap - Input and Output8Functions
Understanding FunctionsDeclaring a FunctionCalling FunctionsFunction ParametersReturning a Single ValueReturning Multiple ValuesNamed Return ValuesFunction Scope BasicsRecap - Creating Reusable Code3Basic Operators
Arithmetic OperatorsDivision OperatorThe Modulo OperatorAssignment OperatorAugmented Assignment OperatorsIncrement and DecrementRecap - Calculations6Control Flow: Conditionals
The `if` StatementThe `else` KeywordThe `else if` KeywordVariable Shadowing in `if`Initializing VariablesThe `switch` StatementSwitch with ExpressionsSwitch without ExpressionThe `fallthrough` KeywordRecap - Making Decisions