Skip to main content

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

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
  }
}