if Statement
Start with Go if Statement
An if statement runs a block only when a condition is true. It lets a program make a decision rather than executing every statement unconditionally.
What you’ll learn
- Write a boolean if condition.
- Trace both true and false paths.
- Explain when statements inside a block execute.
Understand the idea
The form is if condition { ... }. Go does not require parentheses around the condition, but it does require braces around the block. The condition must evaluate to a bool.
When the condition is false, Go skips the block and continues after it. You can place an optional short initialization statement before the condition using a semicolon; keep the first examples simple while you learn the flow.
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() {
temperature := 34
if temperature > 30 {
fmt.Println("It is a hot day")
}
fmt.Println("Weather check complete")
}
Output
It is a hot day
Weather check completeTrace what the program does
Go evaluates temperature > 30. Since 34 is greater than 30, it enters the block, prints the hot-day message and then prints the final line. If the value were 25, only the last line would appear.
Avoid common mistakes
- A condition such as
if temperature { ... }is invalid because an integer is not a boolean. - The opening brace must stay on the condition line in normal Go syntax.
Try it yourself
Change the temperature to 28 and predict what prints. Then add a second independent if that prints a message when the temperature is below 20.
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 if Statement 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.