Go If and Else
An if statement is code that runs its block only when its condition is true. The else block runs when that condition is false.
An if block
The condition is true here. The block runs and prints its line.
package main
import "fmt"
func main() {
age := 20
if age >= 18 {
fmt.Println("Adult")
}
}If and else
The guessed code does not match the stored code. The else block runs instead.
package main
import "fmt"
func main() {
code := 4321
guess := 1234
if guess == code {
fmt.Println("Unlocked")
} else {
fmt.Println("Try again.")
}
}An else if chain
The chain tests each condition in order. The score reaches the second band.
package main
import "fmt"
func main() {
score := 85
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")
}
}A short statement in if
The part before the semicolon sets n for this statement. The condition then tests that same value.
package main
import "fmt"
func main() {
if n := 7; n > 0 {
fmt.Println("Positive")
}
}Example
package main
import "fmt"
func main() {
temperature := 28
if temperature >= 25 {
fmt.Println("Wear light clothes.")
} else if temperature >= 15 {
fmt.Println("Wear a light jacket.")
} else {
fmt.Println("Wear a warm coat.")
}
}Key points
- Use if to run a block when a condition is true.
- Use else to run a block when the condition is false.
- Use else if to test a new condition after a false one.
- Only the first true branch in a chain runs.
- A short statement before the semicolon can set up a value for the condition.
In this example, temperature is 28. The first condition asks if 28 is at least 25. That condition is true, so the first block runs. The printed line is "Wear light clothes.".
Note
An if condition in Go needs no parentheses around it.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Go Playground
Exercise
When does an else block run?