Go
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions and Methods
-
Section 4: Concurrency
-
Section 5: Packages and Tooling
-
Section 6: More Standard Library
-
Section 7: Building Services
-
Section 8: Advanced Go
-
Section 9: Go in the Cloud-Native Ecosystem
-
Section 10: Data Structures and Algorithms in Go
-
Section 11: Testing and Deployment
-
Section 12: Practical Projects
-
Section 13: More Standard Library Practice
-
Section 14: More Practice Projects
-
Section 15: Design Patterns in Go
-
Section 16: Interview Practice
-
Section 17: Package fmt In Depth
-
Section 18: Package strings and strconv
-
Section 19: Package os and io
-
Section 20: Package time
-
Section 21: Package sort and container
-
Section 22: Package encoding
-
Section 23: Package net/http In Depth
-
Section 24: Package context
-
Section 25: Package regexp and bytes
-
Section 26: Package errors In Depth
-
Section 27: Package crypto and hash
-
Section 28: Package flag and log
-
Section 29: Package sync In Depth
-
Section 30: More Practice Exercises
-
Section 31: Go Modules and Workspaces In Depth
-
Section 32: Generics Deep Dive (Go 1.18+)
-
Section 33: Testing Package In Depth
-
Section 34: More Interview and Whiteboard Practice
-
Section 35: Package math and unicode
-
Section 36: Package path and filepath
-
Section 37: Package database/sql
-
Section 38: Package text/template and html/template
-
Section 39: Package archive and compress
-
Section 40: Lower-Level net Package
-
Section 41: Package runtime and reflect
-
Section 42: Package embed and io/fs
-
Section 43: Go Assembly and CGO Basics
-
Section 44: Building CLIs and TUIs
-
Section 45: Go Performance Tuning
-
Section 46: More Real-World Projects
-
Section 47: Go in Production
-
Section 48: Go Design Patterns
-
Section 49: Go Interfaces Deep Dive
-
Section 50: Final Practice and Review
10: Switch Statements
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") andisActive(a boolean). - Use a tagless switch (a switch without a value) to evaluate the following logic:
- If
isActiveisfalse, print "Account disabled. Please renew." - If
tieris "Enterprise", print "Full access: Dedicated support and unlimited seats." - If
tieris "Pro", print "Limited access: Advanced analytics enabled." - If
tieris "Basic", print "Basic access: Core features only." - For any other tier, print "Unknown subscription level."
- If
Test your code by changing the tier and isActive variables to ensure the logic flows correctly!
There are no comments for now.