Learn Go · 3/18

Control Flow: Directing Your Code

8 min read

📜 Control Flow: Directing Your Code

Welcome, Gopher! So far, we've been writing code that runs straight from top to bottom. But what if we want our programs to make decisions? What if we need them to do things repeatedly? That's like trying to build a self-driving car that can only go straight. Not very useful if there's a wall ahead!

This is where control flow comes in. It's the traffic cop of your code, directing the flow of execution based on different conditions. It allows your program to react to input, repeat actions, and make choices, turning a simple script into a dynamic and intelligent application. Let's learn how to tell our code where to go.


1. Conditional Logic: If and Else Statements 🚦

The Problem: Imagine you're writing a program that checks if a user is old enough to vote. The program needs to check the user's age and print one message if they are old enough and a different message if they are not. How can we make the program choose which path to take?

The Solution: We use if and else statements. These are the most fundamental decision-making tools in programming. An if statement checks if a certain condition is true and, if it is, executes a block of code.

Here's the basic structure:

go
package main

import "fmt"

func main() {
    age := 19

    if age >= 18 {
        fmt.Println("You are old enough to vote!")
    }
}

Under the Hood: In Go, the condition inside the if statement must result in a boolean value (true or false). Unlike many other languages, you don't need parentheses () around the condition, but the curly braces {} are always required.

Adding an else clause

What if the condition is false? That's where else comes in. The else block runs only when the if condition is false.

go
package main

import "fmt"

func main() {
    age := 16

    if age >= 18 {
        fmt.Println("You are old enough to vote!")
    } else {
        fmt.Println("Sorry, you are not old enough to vote yet.")
    }
}

A funny little rule: In Go, the else must be on the same line as the closing brace } of the if statement. It's one of Go's quirky formatting rules that actually helps keep code consistent and readable!

Chaining conditions with else if

Sometimes you have more than two possibilities. Let's say you want to categorize a number as positive, negative, or zero. You can chain conditions together using else if.

go
package main

import "fmt"

func main() {
    num := 0

    if num > 0 {
        fmt.Println("The number is positive.")
    } else if num < 0 {
        fmt.Println("The number is negative.")
    } else {
        fmt.Println("The number is zero!")
    }
}

The conditions are checked from top to bottom, and only the code block for the first true condition is executed.

Industry Practice: The if with a short statement

Go has a neat feature where you can declare a variable right before the condition. The scope of this variable is limited to the if and else blocks. This is incredibly common for handling functions that return a value and an error.

go
package main

import (
    "fmt"
    "strconv"
)

func main() {
    // numStr could be from user input or a file
    numStr := "123"

    if num, err := strconv.Atoi(numStr); err == nil {
        fmt.Println("Successfully converted! The number is:", num)
    } else {
        fmt.Println("Failed to convert:", err)
        // The 'num' variable is not accessible here
    }
}

This pattern keeps your code clean by localizing variables to where they are needed.


2. The Mighty switch Statement 🕹️

The Problem: Your if-else if-else chain is getting long and clumsy. You're checking the same variable against many different possible values. It works, but it looks messy and is hard to read. Isn't there a more elegant way?

The Solution: Yes, the switch statement! A switch is a clean way to handle multiple conditions on the same variable. It’s like a super-organized if-else ladder.

Here's a basic example:

go
package main

import (
    "fmt"
    "time"
)

func main() {
    today := time.Now().Weekday()

    switch today {
    case time.Saturday:
        fmt.Println("It's Saturday, time to relax!")
    case time.Sunday:
        fmt.Println("It's Sunday, the weekend is almost over!")
    default:
        fmt.Println("It's a weekday, back to work.")
    }
}

Interesting Fact: Unlike C or Java, switch cases in Go have an implicit break. This means the code doesn't "fall through" to the next case automatically, which is a common source of bugs in other languages. If you want to fall through, you have to use the fallthrough keyword explicitly (but this is rarely used in practice).

Power-ups for your switch

Go's switch is more flexible than in many other languages.

  • Multiple expressions per case: You can group multiple values in a single case.

    go
    switch today {
    case time.Saturday, time.Sunday:
        fmt.Println("It's the weekend!")
    default:
        fmt.Println("It's a weekday.")
    }
  • Expressionless switch: You can use a switch without an expression, making it behave like a clean if-else chain. This is great for checking a range of conditions.

    go
    package main
    
    import "fmt"
    
    func main() {
        score := 85
    
        switch {
        case score >= 90:
            fmt.Println("Excellent! A+")
        case score >= 80:
            fmt.Println("Good job! B")
        case score >= 70:
            fmt.Println("Not bad. C")
        default:
            fmt.Println("Keep trying! D")
        }
    }

3. Looping in Go: The Versatile for Loop 🔄

The Problem: You need to send a "Happy Birthday!" message to 100 people. Are you going to copy and paste the fmt.Println() line 100 times? Please don't. That's a recipe for carpal tunnel and unmaintainable code.

The Solution: Use a loop! A loop allows you to execute a block of code repeatedly.

Interesting Fact: Go is a minimalist's dream. It only has one looping construct: the for loop. But this single for loop is incredibly versatile and can be used in several ways.

The Classic for Loop

This is the most common type of loop, similar to for loops in other C-style languages. It has three parts separated by semicolons: for [initialization]; [condition]; [post-statement].

  1. Initialization: Runs once before the loop starts.
  2. Condition: Checked before every iteration. The loop continues as long as it's true.
  3. Post-statement: Runs at the end of every iteration.
go
package main

import "fmt"

func main() {
    // Prints numbers 0 through 4
    for i := 0; i < 5; i++ {
        fmt.Println("The count is:", i)
    }
}

The "While" Loop

You can omit the initialization and post-statements to make the for loop act like a while loop from other languages. It will run as long as the condition is met.

go
package main

import "fmt"

func main() {
    powerLevel := 1
    // This loop continues as long as powerLevel is less than 9000
    for powerLevel < 9000 {
        fmt.Println("Power level:", powerLevel)
        powerLevel *= 2
    }
    fmt.Println("It's over 9000!")
}

The Infinite Loop

If you omit all parts, you get an infinite loop. This is useful for servers that need to continuously listen for requests or for programs that should run forever until manually stopped.

go
package main

import (
    "fmt"
    "time"
)

func main() {
    for {
        fmt.Println("This will run forever... or until you press Ctrl+C")
        time.Sleep(1 * time.Second)
    }
}

You'll almost always pair an infinite loop with a condition inside that can stop it (we'll see how in the next section!).


4. Controlling Loops: break and continue 🛑➡️

The Problem: You're in a loop, searching for a specific item in a huge list. Once you find it, there's no point in continuing to search through the rest of the list. Or, maybe you are processing items but want to skip certain ones that don't meet a criterion. How do you gain finer control over your loop's execution?

The Solution: break and continue are two keywords that alter the normal flow of a loop.

break: The Emergency Exit

The break statement terminates the loop immediately. It’s like pulling the emergency brake on a train. The loop stops, and the program continues with the code that comes right after the loop.

Imagine a bomb defusal scenario. You're looping through wires, and once you find the "defuse" wire, you cut it and break out of the loop. You definitely don't want to keep checking other wires!

go
package main

import "fmt"

func main() {
    for i := 1; i <= 10; i++ {
        if i == 5 {
            fmt.Println("Found the number 5! Breaking out of the loop.")
            break // Exit the loop
        }
        fmt.Println("Checking number:", i)
    }
    fmt.Println("Loop finished.")
}

Output:

livecodeserver
Checking number: 1
Checking number: 2
Checking number: 3
Checking number: 4
Found the number 5! Breaking out of the loop.
Loop finished.

Notice how the numbers after 4 are never checked because break ended the loop.

continue: Skip to the Next

The continue statement skips the current iteration of the loop and moves on to the next one. It’s like telling an assembly line worker, "This one's faulty, just skip it and move to the next item."

Let's print only the odd numbers from 1 to 10.

go
package main

import "fmt"

func main() {
    for i := 1; i <= 10; i++ {
        if i%2 == 0 { // If the number is even...
            continue // ...skip to the next iteration
        }
        fmt.Println(i)
    }
}

Output:

text
1
3
5
7
9

When i is an even number, the continue statement is executed, and the fmt.Println(i) line is skipped for that iteration.


📚 Extra Reading & References

Challenge

You are tasked with building a function for a logistics company to calculate shipping costs. Your goal is to implement the calculateShippingCosts function.

This function accepts a slice of Package structs. You must process each package according to the following rules, applying various control flow mechanisms.

Requirements:

  1. Iterate through the packages slice using a for loop.
  2. For each package, first call the provided validatePackage function. Use an if statement with a short variable declaration to capture and check for an error. If an error is returned (i.e., the error is not nil), you must skip the current package and proceed to the next one using the continue keyword.
  3. If a package has its isHighPriority field set to true, calculate its cost, add it to the total, and then immediately terminate the loop using the break keyword. No subsequent packages should be processed.
  4. Determine the base shipping cost using a switch statement on the destinationZone:
    • Zone "A": $10.00
    • Zone "B": $15.00
    • Zone "C": $20.00
    • Any other zone: $25.00
  5. After determining the base cost, add a weight-based surcharge using an if-else if-else chain:
    • Weight > 10.0: +$10.00
    • Weight > 5.0 and <= 10.0: +$5.00
    • (No surcharge for weights 5.0 or less)
  6. If the package's isFragile field is true, add an additional flat fee of $3.00.
  7. The function must return the cumulative total cost of all processed packages as a float64.

Expected result

Your calculateShippingCosts function should be correctly implemented to meet all the specified requirements.

  • It must loop through the input slice of packages.
  • It must use an if statement with a short declaration to call validatePackage and correctly use continue to skip packages that return an error.
  • It must correctly use break to exit the loop immediately after processing the first isHighPriority package.
  • A switch statement must be used to correctly assign the base cost based on the destinationZone.
  • An if-else if-else structure must be implemented to accurately add weight-based surcharges.
  • A simple if statement must be used to add the fragile handling fee.
  • The function should accumulate the costs correctly and return the final total as a float64.
go

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.