The if Statement #
Use the if statement to specify a block of Go code to be executed if a condition is true.
Syntax #
if condition {
// code to be executed if condition is true
}Note:
ifmust be lowercase. UsingIforIFwill generate an error.
Example 1: Using values directly #
package main
import ("fmt")
func main() {
if 20 > 18 {
fmt.Println("20 is greater than 18")
}
}Example 2: Using variables #
package main
import ("fmt")
func main() {
x := 20
y := 18
if x > y {
fmt.Println("x is greater than y")
}
}Example explained #
In the example above, we use two variables, x and y, to test whether x is greater than y using the > operator.
Since x is 20 and y is 18, the condition evaluates to true, and the following is printed:
x is greater than y