Make decisions with if
Choose different behavior based on a condition.
- Use if and else to select a result.
An if statement runs a block only when its condition is true. Add else for the other path. Go does not wrap conditions in parentheses, but braces are required. A short variable declaration can appear before the condition.
1package main
2
3import "fmt"
4
5func main() {
6 score := 82
7 if score >= 60 {
8 fmt.Println("pass")
9 } else {
10 fmt.Println("try again")
11 }
12}pass
Conditions evaluate to a bool. Comparison operators include ==, !=, <, <=, >, and >=. Keep the else attached to the closing brace of the if block.
Key takeaways
Use if and else to select a result.
Go catches many mistakes while compiling.
Use small experiments to understand each new language feature.
Lesson quiz
4 questions · pass with 3 correct · up to 50 XP
Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.
Practice: write Go
Write Go in the editor and run it against sample input with a remote compiler. Your code is sent to Compiler Explorer to compile and run.
Label a temperature
Read an integer temperature. Print cold if it is below 15; otherwise print warm.
- Below threshold
- At threshold
Go is compiled and run by Compiler Explorer (godbolt.org), a free public service. Your source code and test input are sent to that service.
Questions about this lesson
Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.
Loading posts…