Skip to Content
Course content
Click on the "Edit" button in the top corner of the screen to edit your slide content.

A few years ago, I was reviewing a pull request for a colleague who was building a payment gateway integrator. He had written a block of code to handle different currency symbols that was nearly 60 lines long—just a massive, cascading wall of if currency == "USD", else if currency == "EUR", and so on. It was technically correct, but it was a nightmare to read. Every time I looked at it, I felt like I was staring at a staircase that never ended. I told him, "You're working too hard. This is exactly why the switch statement exists."

Tidying Up Your Conditional Logic

In Go, a switch statement is essentially a cleaner way to write a long chain of if-else blocks. The biggest relief for people coming from C++ or Java is that Go has an implicit break. You don't have to remember to put a break at the end of every case, or you'll accidentally execute the next block of code. Once a case matches, Go executes that block and then exits the switch entirely.

package main

import "fmt"

func main() {
    paymentMethod := "PayPal"

    switch paymentMethod {
    case "CreditCard":
        fmt.Println("Processing via Stripe...")
    case "PayPal":
        fmt.Println("Redirecting to PayPal portal...")
    case "Bitcoin":
        fmt.Println("Verifying wallet address...")
    default:
        fmt.Println("Unsupported payment method.")
    }
}

I personally prefer using the default case almost every single time. Even if you think you've covered every possible scenario, the default block acts as a safety net for unexpected input, which is vital when you're dealing with external API data.

Switching Without a Value

Here is where Go gets interesting. You aren't limited to comparing a single variable against a list of values. You can actually write a switch statement without any expression at all. When you do this, the switch behaves like a cleaner version of an if-else if chain because it evaluates each case as a boolean expression.

This is incredibly useful when you have complex ranges or multiple different variables to check in one block. Instead of nesting if statements inside other if statements, you can just list your conditions clearly.

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")
}

Handling Overlap with Fallthrough

Every now and then, you'll encounter a situation where you actually want the code to move into the next case. In Go, we use the fallthrough keyword for this. It's a bit of a rare beast—I'll be honest, I rarely use it in my own production code—but it's there for when you need a specific piece of logic to trigger a subsequent case regardless of whether that case's condition is met.

Just be careful. fallthrough doesn't check the condition of the next case; it just blindly jumps into it. If you use it too often, you end up creating the same "spaghetti code" that we were trying to avoid by moving away from nested if statements in the first place.




📋 Practical Task

Building a Multi-Tier Subscription Validator

You are building a feature for a SaaS application that determines what features a user can access based on their subscription tier and their account status. Your goal is to create a program that evaluates these conditions using a switch statement.

Create a program with the following requirements:

  • Define two variables: tier (a string, e.g., "Basic", "Pro", "Enterprise") and isActive (a boolean).
  • Use a tagless switch (a switch without a value) to evaluate the following logic:
    • If isActive is false, print "Account disabled. Please renew."
    • If tier is "Enterprise", print "Full access: Dedicated support and unlimited seats."
    • If tier is "Pro", print "Limited access: Advanced analytics enabled."
    • If tier is "Basic", print "Basic access: Core features only."
    • For any other tier, print "Unknown subscription level."

Test your code by changing the tier and isActive variables to ensure the logic flows correctly!

Rating
0 0

There are no comments for now.

to be the first to leave a comment.