If & Switch Statements
Control flow statements let your program make decisions. In this lesson, you'll learn how to use if statements for simple conditions and switch statements for multiple choices, making your Go programs dynamic and responsive.
If Statements
The if statement executes code when a condition is true. Unlike many
languages,
Go doesn't require parentheses around the condition:
Click Run to execute your code
- No parentheses needed around the condition
- Braces
{}are required, even for single statements - Opening brace must be on the same line as
if - Conditions must be boolean expressions
If-Else and Else If
// If-else
if age >= 18 {
fmt.Println("Adult")
} else {
fmt.Println("Minor")
}
// Else if chain
if score >= 90 {
fmt.Println("Grade: A")
} else if score >= 80 {
fmt.Println("Grade: B")
} else if score >= 70 {
fmt.Println("Grade: C")
} else {
fmt.Println("Grade: F")
}
if (x > 5) with
parentheses
around the condition. Also, the condition must be a boolean—no truthy/falsy
values like in
JavaScript or Python!
If with Short Statement
Go allows you to execute a short statement before the condition. This is useful for limiting variable scope:
Click Run to execute your code
Common Pattern: Error Checking
// Common Go pattern
if err := doSomething(); err != nil {
fmt.Println("Error:", err)
return
}
// err is not accessible here
// Another example
if value, ok := myMap["key"]; ok {
fmt.Println("Found:", value)
} else {
fmt.Println("Not found")
}
Switch Statements
Switch statements provide a cleaner way to write multiple if-else conditions:
Click Run to execute your code
- No
breakneeded—cases don't fall through by default - Can have multiple values in a case
- Cases can be expressions, not just constants
- Can switch without a condition (like if-else chain)
Switch Without Condition
A switch without a condition is the same as switch true, making it a
cleaner
if-else chain:
hour := time.Now().Hour()
switch {
case hour < 12:
fmt.Println("Good morning!")
case hour < 18:
fmt.Println("Good afternoon!")
default:
fmt.Println("Good evening!")
}
Multiple Values in Case
day := "Saturday"
switch day {
case "Saturday", "Sunday":
fmt.Println("It's the weekend!")
case "Monday":
fmt.Println("Start of the week")
default:
fmt.Println("It's a weekday")
}
Fallthrough
If you need C-style fallthrough behavior, use the fallthrough
keyword:
switch num := 2; num {
case 1:
fmt.Println("One")
case 2:
fmt.Println("Two")
fallthrough // Continues to next case
case 3:
fmt.Println("Three")
}
// Output: Two
// Three
fallthrough is rarely needed in Go. The
default
non-fallthrough behavior is usually what you want!
Type Switch
Type switches allow you to compare types instead of values. This is useful when working with interfaces:
Click Run to execute your code
switch v := i.(type) {
case int:
// v is an int
case string:
// v is a string
default:
// v has the same type as i
}
If vs Switch: When to Use Which?
| Use If When... | Use Switch When... |
|---|---|
| Simple true/false condition | Multiple specific values to check |
| Range comparisons (<, >, etc.) | Equality checks against constants |
| Complex boolean logic | Type checking (type switch) |
| 2-3 conditions max | 4+ conditions |
Common Mistakes
1. Using non-boolean conditions
// ❌ Wrong - won't compile
x := 5
if x { // Error: non-bool used as if condition
fmt.Println("x is truthy")
}
// ✅ Correct - explicit comparison
if x != 0 {
fmt.Println("x is not zero")
}
2. Missing braces
// ❌ Wrong - syntax error
if x > 5
fmt.Println("Greater")
// ✅ Correct - braces required
if x > 5 {
fmt.Println("Greater")
}
3. Expecting switch fallthrough
// ❌ Wrong expectation (from C/Java)
switch x {
case 1:
fmt.Println("One")
case 2:
fmt.Println("Two")
}
// Only prints "One" if x is 1, not "One" and "Two"
// ✅ Correct - Go doesn't fall through by default
// This is actually the desired behavior!
4. Opening brace on wrong line
// ❌ Wrong - syntax error
if x > 5
{
fmt.Println("Greater")
}
// ✅ Correct - brace on same line
if x > 5 {
fmt.Println("Greater")
}
Exercise: Grade Calculator
Task: Create a program that determines letter grades and provides feedback.
Requirements:
- Take a score variable (use 85)
- Use if-else to determine the letter grade:
- 90-100: A
- 80-89: B
- 70-79: C
- 60-69: D
- Below 60: F
- Use switch to provide feedback based on grade
- Print both grade and feedback
Show Solution
package main
import "fmt"
func main() {
score := 85
var grade string
// Determine letter grade
if score >= 90 {
grade = "A"
} else if score >= 80 {
grade = "B"
} else if score >= 70 {
grade = "C"
} else if score >= 60 {
grade = "D"
} else {
grade = "F"
}
fmt.Printf("Score: %d, Grade: %s\n", score, grade)
// Provide feedback based on grade
switch grade {
case "A":
fmt.Println("Excellent work!")
case "B":
fmt.Println("Good job!")
case "C":
fmt.Println("Satisfactory")
case "D":
fmt.Println("Needs improvement")
case "F":
fmt.Println("Please see instructor")
}
// Bonus: Check if passing
switch {
case score >= 60:
fmt.Println("Status: Passing")
default:
fmt.Println("Status: Failing")
}
}
Summary
- if statements execute code when conditions are true
- No parentheses needed around conditions in Go
- Braces required even for single statements
- Short statements in if limit variable scope
- switch statements provide cleaner multi-way branches
- No break needed in switch—cases don't fall through
- Multiple values allowed in switch cases
- Switch without condition acts like if-else chain
- Type switch compares types instead of values
What's Next?
Now that you can make decisions in your code, it's time to learn about Loops & Range. In the next lesson, you'll discover how to repeat code execution and iterate over collections.
Enjoying these tutorials?