Making Your Code "Think"
So far, our code has been executing line by line, from top to bottom. But what if we want it to make decisions? What if we want it to do one thing if a user is logged in, and something else if they aren't?
This is where conditional logic comes in. It's the "brain" of our program, allowing it to react differently to different situations. In Go, we have two primary tools for this: the if statement and the switch statement.
1. The if Statement: The Classic Decision Maker
The if statement is the most fundamental way to make a decision. Its logic is simple: "IF a certain condition is true, then do this."
We can extend it with else if for more conditions, and else for a default action if no conditions are met.
Analogy: A fork in the road. You check the sign (if condition), and based on that, you choose a path.
How to Use if-else
Let's build a simple program that gives a grade based on a score.
package main
import "fmt"
func main() {
score := 85
// The program checks these conditions from top to bottom
if score > 90 {
fmt.Println("Grade: A (Excellent!)")
} else if score > 80 {
fmt.Println("Grade: B (Good)")
} else if score > 70 {
fmt.Println("Grade: C (Average)")
} else {
fmt.Println("Grade: D (Needs Improvement)")
}
}
How it works:
- Since
scoreis 85, the first condition (> 90) is false. - It moves to the next one.
score > 80is true! - The code inside that block runs, printing "Grade: B (Good)".
- The rest of the
if-elsechain is then skipped.
2. The switch Statement: The Tidy Alternative
Sometimes, you have a long chain of if-else if statements that all check the same variable. This can look a bit messy. For these situations, Go gives us the switch statement, which is often cleaner and easier to read.
Analogy: A vending machine menu. You check one thing (the button the user pressed) and match it against a list of possible options.
How to Use switch
Let's rewrite a decision-making process for the days of the week.
package main
import "fmt"
func main() {
day := "Saturday"
switch day {
case "Monday":
fmt.Println("Time to start the week!")
case "Friday":
fmt.Println("The weekend is almost here!")
case "Saturday", "Sunday": // You can group multiple cases
fmt.Println("It's the weekend!")
default:
// This runs if no other case matches
fmt.Println("It's a regular day.")
}
}
How it works:
- Go takes the
dayvariable ("Saturday"). - It checks each
caseone by one. - It finds a match in
case "Saturday", "Sunday":. - The code inside that block runs, and the
switchstatement ends. - The
defaultblock is the equivalent of the finalelsein anifchain.
if vs. switch: When to Use Which?
Here's a simple rule of thumb:
- Use
if-elsewhen you have complex conditions, check ranges (likescore > 90), or need to evaluate multiple different variables. - Use
switchwhen you are checking a single variable against a list of specific, exact values.
Conclusion
You've now learned how to give your Go programs a "brain"! Using if and switch, you can control the flow of your code, allowing it to make decisions and react dynamically. This is a massive step up from simply running code from top to bottom.
In the next part of our series, we'll learn how to make our programs perform tasks repeatedly without rewriting code, by mastering Go's only loop: the powerful for loop. See you there!
Top comments (0)