Go Nested if Statement

In Go, you can nest if statements within other if statements, allowing for more intricate logical evaluations. This is called a “nested if” statement and is particularly useful for scenarios where multiple related conditions need to be checked.

Tutorials dojo strip



Syntax

The general structure of a nested if statement is:

Go




Example: Nested Conditions with Motorcycle Ratings

Go

Explanation of Example

In this code:

  • The program checks the variable suzukiRating, which is set to 20.
  • The first if statement verifies whether the rating is greater than or equal to 10. Since this condition is true, the program prints “Suzuki’s rating is more than or equal to 10.”
  • Within the first if block, another if statement checks if the rating exceeds 15. Since this condition is also true, it prints “Suzuki’s rating is also more than 15.”
  • If the initial condition (suzukiRating >= 10) were false, the else block would execute, displaying “Suzuki’s rating is less than 10.”

Result:

Go
Tutorials dojo strip