Nested if Statement

Nested if Statement #

You can have if statements inside other if statements. This is called a nested if.

Syntax #

if condition1 {
   // code to be executed if condition1 is true
   if condition2 {
      // code to be executed if both condition1 and condition2 are true
   }
}

Example #

This example shows how to use nested if statements:

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.")
  }
}

Result:

Num is more than 10.
Num is also more than 15.

Example explained #

  • num is 20, so the first condition (num >= 10) is true.
  • The program prints “Num is more than 10.”
  • Inside that block, the second condition (num > 15) is also true.
  • The program prints “Num is also more than 15.”
  • If num were less than 10, only the else block would execute.