The if Statement
An if statement runs a block of Go code only when its condition is true.
Note: Always write if in lowercase. Go treats If or IF as an error.
Example
This program compares two numbers, 20 and 18. Because 20 is the larger one, the condition is true and the text gets printed:
Prompt
Use the if statement to check if 20 is greater than 18 and print a message.
Output: Go program and captured output
main.go
package main
import ("fmt")
func main() {
if 20 > 18 {
fmt.Println("20 is greater than 18")
}
}
If Statement Syntax
main.go
if condition {
// code to be executed if condition is true
}
Test Variables
Conditions aren't limited to fixed numbers. They can check variables too:
Example
This time the comparison uses two variables, x and y, and the > operator checks whether x is the larger one. With x holding 20 and y holding 18, the answer is yes, so the program prints "x is greater than y".
Prompt
Use the if statement to compare two variables and print which is greater.
Output: Go program and captured output
main.go
package main
import ("fmt")
func main() {
x := 20
y := 18
if x > y {
fmt.Println("x is greater than y")
}
}