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.
Syntax
The general structure of a nested if
statement is:
Go
x
if condition1 {
// Code executed if condition1 is true
if condition2 {
// Code executed if both condition1 and condition2 are true
}
}
Example: Nested Conditions with Motorcycle Ratings
Go
package main
import ("fmt")
func main() {
suzukiRating := 20
if suzukiRating >= 10 {
fmt.Println("Suzuki's rating is more than or equal to 10.")
if suzukiRating > 15 {
fmt.Println("Suzuki's rating is also more than 15.")
}
} else {
fmt.Println("Suzuki's rating is less than 10.")
}
}
Explanation of Example
In this code:
- The program checks the variable
suzukiRating
, which is set to20
. - The first
if
statement verifies whether the rating is greater than or equal to10
. Since this condition is true, the program prints “Suzuki’s rating is more than or equal to 10.” - Within the first
if
block, anotherif
statement checks if the rating exceeds15
. Since this condition is also true, it prints “Suzuki’s rating is also more than 15.” - If the initial condition (
suzukiRating >= 10
) were false, theelse
block would execute, displaying “Suzuki’s rating is less than 10.”
Result:
Go
Suzuki's rating is more than or equal to 10.
Suzuki's rating is also more than 15.