Nested if Statement in Go
Go allows you to place an if statement inside another if — this is called a nested if. It is useful when you want to check multiple related conditions.
syntax
if condition1 {
// code runs if condition1 is true
if condition2 {
// code runs if both condition1 and condition2 are true
}
}
Example: Nested if in Action
In the example below, the program checks if num is greater than or equal to 10.
If true, it then checks a second condition: whether num is also greater than 15.
package main
import "fmt"
func main() {
num := 20
if num >= 10 {
fmt.Println("num is greater than or equal to 10.")
if num > 15 {
fmt.Println("num is also greater than 15.")
}
} else {
fmt.Println("num is less than 10.")
}
}
Output:
num is greater than or equal to 10.
num is also greater than 15.