Lesson contents

Go — If, else if, and else

Go uses boolean expressions to choose branches. Test the most restrictive condition first when two conditions can cover the same request.

A simple example

Follow one branch

  1. Start with n is 2
  2. Do this Is n positive?
  3. Result yes
The condition selects the first branch. Changing the value to zero selects the other branch.
main.go
package main

import "fmt"


func main() {
    n := 2
    if n > 0 {
        fmt.Println("yes")
    } else {
        fmt.Println("no")
    }
}
Output
yes
Advertisements

Classify a stock request

Check whether a request is positive before comparing it with the available stock. Select one action for an invalid, fillable, or deferred request. Braces delimit the branches. The second condition can assume that the request is positive because the first condition already handled the other values.

Available: 3 calculators. Request exactly 3: Accept. Request 8: Defer.
Decide which orders to fill

The equipment desk has three calculators to lend. A request for a negative quantity is invalid, three can be filled exactly, and eight must wait. Each request produces one decision.

Run the example

Use Go 1.21 or later. Run these commands from the directory containing the example.

go run main.go
main.go
package main

import (
	"fmt"
)

func main() {
	available := 3
	for _, request := range []int{-1, 3, 8} {
		if request <= 0 {
			fmt.Println("invalid")
		} else if request <= available {
			fmt.Println("accept")
		} else {
			fmt.Println("defer")
		}
	}
}
Output
invalid
accept
defer

With three in stock, −1 is invalid, 3 can be filled exactly, and 8 must be deferred. Only the first matching branch runs.

Try it yourself

What should happen for a request of zero?

Check your answer

The first branch rejects it as invalid. Checking the stock limit first would incorrectly treat zero as fillable.

Go language specification

Related tags

  • Go
  • if
  • else
  • branch order