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
- Start with n is 2
- Do this Is n positive?
- Result yes
package main
import "fmt"
func main() {
n := 2
if n > 0 {
fmt.Println("yes")
} else {
fmt.Println("no")
}
}
yes
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.
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
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")
}
}
}
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.