Skip to Content
Course content

8: Control Flow: If/Else

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

Wait, do I really not need parentheses around the condition?

If you're coming from Java, C#, or JavaScript, your fingers are probably itching to type if (x > 10). In Go, we drop the parentheses. You just write if x > 10 { ... }. Trust me, once you get used to it, the code feels much cleaner and less cluttered.

One thing you cannot skip, however, are the curly braces. Even if your if-block is only one line long, Go requires the braces. I've seen plenty of beginners try to omit them, but the compiler will shut you down immediately. It's a design choice to keep the code consistent and avoid those classic "dangling else" bugs that haunt other languages.

// This is the Go way
if userAge >= 18 {
    fmt.Println("Access granted")
}

How do I handle multiple different conditions?

It works exactly how you'd expect: you use else if and else. The key is that Go evaluates these in order. As soon as it finds a condition that is true, it executes that block and skips the rest of the chain.

Let's say we're building a simple logic gate for a server's health check. We want to categorize the status based on response time:

responseTime := 450 // in milliseconds

if responseTime < 200 {
    fmt.Println("System is Healthy")
} else if responseTime < 500 {
    fmt.Println("System is Slow")
} else {
    fmt.Println("System is Critical")
}

I usually suggest keeping these chains relatively short. If you find yourself writing ten else if blocks in a row, you might want to reconsider using a switch statement instead (which we'll hit in a later lesson).

What is that weird semicolon doing inside my if statement?

You'll often see Go code that looks like this: if err := doSomething(); err != nil { ... }. This is one of my favorite idiomatic features of the language. It's called an "if with a short statement."

Essentially, Go lets you initialize a variable and check its value in one single line. The magic part? The variable you create (in this case, err) is only scoped to the if/else blocks. It doesn't leak out into the rest of your function.

This is incredibly useful for keeping your namespace clean. Here is a practical example where we check if a user is "Active" before proceeding:

// Imagine checkStatus() returns a boolean and an error
if active, err := checkStatus(userID); err != nil {
    fmt.Println("Error checking status:", err)
} else if !active {
    fmt.Println("User account is deactivated")
} else {
    fmt.Println("User is active! Proceeding...")
}
// 'active' and 'err' are not accessible here; they died with the if block.

I use this pattern constantly, especially when handling errors. It keeps the "setup" logic right next to the "check" logic, which makes the code much easier to read during a code review.




📋 Practical Task

Exercise: Building a Tiered Subscription Access Checker

You are tasked with writing a piece of logic for a SaaS platform. The platform has three tiers: "free", "pro", and "enterprise". You need to determine if a user can access a specific "Advanced Analytics" feature based on their tier.

Requirements:

  • Create a variable userTier (string).
  • Create a variable isAccountSuspended (boolean).
  • Use an if/else if/else structure to implement the following logic:
    • If isAccountSuspended is true, print "Access Denied: Account Suspended".
    • If the tier is "enterprise" or "pro", print "Access Granted".
    • If the tier is "free", print "Access Denied: Please upgrade to Pro".
    • For any other unexpected tier value, print "Access Denied: Invalid Tier".

Bonus: Try to implement the isAccountSuspended check using the "short statement" syntax by initializing a dummy variable within the if line.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.