Gaaker Go

Golang Nested if statement

An if statement can be added after the else, which can handle more than three kinds of branch logic.

if condition1 {
	// do something	
} else if condition2 {
	// do something
} else {
	// catch-all or default
}

There is no limit to the number of else if branches. But for code readability, don’t add too many else if branches after the if statement.

The following is a complete code example.

package main

import "fmt"

func main() {
    age := 67
    if age < 18 {
        fmt.Println("kid")
    } else if age >= 18 && age < 50 {
        fmt.Println("young")
    } else {
        fmt.Println("old")
    }
}

Below is the program output:

old
< Nested if statement Nested if statement >