Conditional Statements
# CHAPTER 7
Conditional Statements
1. Introduction
A program that executes the exact same lines of code every single time is not very intelligent. Real applications must react to data: *If* a user's password is correct, log them in; *Else*, deny access. Conditional Statements allow your Go programs to make logical decisions and branch out into different execution paths.2. Learning Objectives
By the end of this chapter, you will be able to:-
Use the
ifstatement to evaluate boolean conditions.
-
Implement
if-elseandelse iffor multiple decision paths.
-
Understand Go's strict syntax rules regarding braces
{ }.
-
Use the
switchstatement as a cleaner alternative to longifchains.
3. The if Statement
The if statement evaluates a condition. If the condition is true, the code inside the block executes. If false, it is skipped.
Syntax Rule: Unlike C++ or Java, Go intentionally removes the parentheses () around the condition to make the code cleaner.
4. The if-else and else if Statements
To handle multiple scenarios, we chain conditions together.
CRITICAL Syntax Rule: The else keyword MUST be on the exact same line as the closing brace } of the preceding if block.
5. Short Statement in if
Go has a unique and powerful feature: you can declare a temporary variable *inside* the if statement before the condition. This variable only exists inside the if block, keeping your memory clean.
This is heavily used in Go for Error Handling (which we will cover in Chapter 16).
6. The switch Statement
When you have an if-else ladder comparing a single variable to many exact values, a switch statement is much cleaner.
Massive Difference from C/Java: In C/Java, if you forget to write break; at the end of a case, the code "falls through" and executes the next case automatically (causing horrible bugs). Go fixed this! In Go, switch cases break automatically. No break keyword is needed!
7. Mini Project: Grade Calculator
Let's combine I/O with conditionals.8. Common Mistakes
-
Adding Parentheses: Writing
if (x > 5)instead ofif x > 5. While the compiler will accept it,gofmtwill immediately delete them because they violate Go's styling standards.
-
Brace Placement: Placing
elseon a new line. Go automatically inserts semicolons at the end of lines. If}is alone on a line, Go inserts a semicolon after it, causing theelseon the next line to become a syntax error.
9. Best Practices
-
Fail Fast (Return Early): Instead of deeply nesting
ifstatements (pyramid of doom), check for errors first and return immediately.
go
// Bad
if data != nil {
if auth == true {
// do work
}
}
// Good (Fail Fast)
if data == nil { return }
if auth == false { return }
// do work
`
10. Exercises
-
1.
Write a program that asks the user for their age. If they are 18 or older, print "Access Granted". Otherwise, print "Access Denied".
-
2.
Write a
switch statement that checks a string variable fruit := "apple". Have cases for "apple", "banana", and a default case.
11. MCQs with Answers & Explanations
Q1. Are parentheses required around the condition in a Go
if statement?
a) Yes b) No
Answer: b) No. *Explanation: Go favors clean, minimalist syntax.*
Question 2
Where MUST the else keyword be placed in Go?
Question 3
What happens if an if condition evaluates to false?
Q4. Can you declare a new variable entirely inside an if statement initialization?
a) Yes (e.g., if x := 10; x > 5) b) No
Answer: a) Yes. *Explanation: This keeps the variable scope local to the if block, freeing up memory faster.*
Q5. In a Go
switch statement, do you need to write break at the end of every case?
a) Yes b) No
Answer: b) No. *Explanation: Go automatically breaks out of the switch after a case executes, preventing fall-through bugs.*
Question 6
Which keyword acts as the catch-all fallback in a switch statement?
Q7. Can if statements be nested inside other if statements?
a) Yes b) No
Answer: a) Yes.
Question 8
What operator is used to check if a value is NOT equal to another?
Question 9
If score := 85, which block executes in an if score >= 90 / else if score >= 80 ladder?
Q10. Which is generally cleaner for checking 10 exact, specific integer values?
a) 10 if-else statements b) A single switch statement
Answer: b) A single switch statement.
12. Interview Preparation
Interview Questions:
-
1.
Why does Go not require the
break keyword in switch statements, unlike C++ or Java?
-
2.
Explain the scope of a variable declared in the short statement of an
if block.
Common Pitfall: Many developers write deeply nested
if blocks. Interviewers love to see candidates refactor nested ifs using the "Return Early / Guard Clause" pattern.
13. Summary
Conditional statements are the brain of your application. The if, else if, and else blocks allow for dynamic logic. The switch` statement handles exact value matching cleanly. Go's design choices—like removing parentheses, requiring specific brace formatting, and auto-breaking switch cases—ensure logic is easy to read and safe from historical bugs.