Day 3: Control Flow in Go: If and Switch Statements

Venkat Annangi
Venkat Annangi
23/09/2024 15:40 2 min read 42 views
#golang #108 days of golang

Day 3: Mastering Conditional Logic in Go - If and Switch

In this session, we’ll dive deep into Go’s conditional logic through if and switch statements. These control structures help us direct the flow of our programs based on different conditions.

Step 1: If Statements

Go’s if statements are simple and do not require parentheses around the condition:

if x > 10 {
    fmt.Println("x is greater than 10")
} else {
    fmt.Println("x is 10 or less")
}

Using Initialization in If

In Go, you can include an initialization statement before the condition:

if y := x * 2; y > 20 {
    fmt.Println("y is greater than 20")
}

Step 2: Switch Statements

Switches in Go are versatile. You can switch on any type of value, and case conditions do not need to be constants:

switch day {
case "Monday":
    fmt.Println("Start of the week")
case "Friday":
    fmt.Println("Weekend is near")
default:
    fmt.Println("Just another day")
}

Switch Without a Condition

You can omit the switch expression altogether, acting like a concise if-else if chain:

switch {
case x < 10:
    fmt.Println("x is less than 10")
case x == 10:
    fmt.Println("x is equal to 10")
default:
    fmt.Println("x is greater than 10")
}

Practical Exercise

Write a program to check if a given number is positive, negative, or zero using an if statement. Then refactor it using a switch statement.

Comments