The Nested if Statement
The body of an if can hold any statement, including another if. Placing one inside the other gives you a nested if: the inner condition is looked at only after the outer one has turned out true.
Example
Here one if sits inside another. Because num is 20, it passes both checks and both messages are printed:
Prompt
Use nested if statements to check if a number is at least 10 and also more than 15.
Set num to 20.
Output: Go program and captured output
main.go
package main
import ("fmt")
func main() {
num := 20
if num >= 10 {
fmt.Println("Num is more than 10.")
if num > 15 {
fmt.Println("Num is also more than 15.")
}
} else {
fmt.Println("Num is less than 10.")
}
}
Nested if Syntax
main.go
if condition1 {
// code to be executed if condition1 is true
if condition2 {
// code to be executed if both condition1 and condition2 are true
}
}