Nested if Statements
Start with Go Nested if Statements
A nested if is an if statement placed inside another conditional block. It is useful when one decision only matters after another condition has passed.
What you’ll learn
- Trace nested conditions.
- Identify which else belongs to which if.
- Consider whether a combined condition is clearer.
Understand the idea
For example, checking a ticket makes sense only after verifying the user is old enough. The inner condition is never evaluated when the outer condition is false. The braces show which else belongs to which if.
Nesting is useful but should not become unnecessarily deep. If several layers make the logic hard to follow, consider guard clauses or extracting functions when you reach those topics.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func main() {
age := 20
hasTicket := false
if age >= 18 {
if hasTicket {
fmt.Println("Entry allowed")
} else {
fmt.Println("Ticket required")
}
} else {
fmt.Println("Age requirement not met")
}
}
Output
Ticket requiredTrace what the program does
The outer condition is true because the age is 20. Go then evaluates hasTicket, which is false, and prints Ticket required. The outer else does not run.
Avoid common mistakes
- Indent nested branches consistently so an
elseis visually associated with its matchingif. - Use
age >= 18 && hasTicketwhen only one combined success condition is needed; nesting can be reserved for different error messages.
Try it yourself
Set age to 16 and hasTicket to true. Explain why the inner condition is never reached.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Go Nested if Statements in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.