Lesson contents

Go — Comparisons and short-circuit operators

Go's && evaluates the right operand only when the left operand is true. Put a slice access after the checks that establish a valid index.

A simple example

Test two conditions

  1. Start with n is 2
  2. Do this Greater than 0 and less than 3?
  3. Result yes
Both comparisons succeed, so the program prints yes.
main.go
package main

import "fmt"


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

Operator examples

Operation Expression Result
Integer division 7 / 2 3
Remainder 7 % 2 1
Comparison 5 >= 5 true
Equality 3 == 4 false
Logical conjunction true && false false
Bit mask 6 & 3 2

Guard an indexed lookup

Combine comparisons with a short-circuiting logical operator. Check that a zero-based index is within bounds before reading the element at that index. A negative or oversized index would cause a runtime panic. Short-circuiting leaves both cases outside the indexed expression.

Shelf quantities: 2 and 5. Order needs: At least 5. Second shelf: 5 available.
Look up a shelf safely

A stock scanner receives a shelf position before it knows whether that shelf exists. Check the bounds first. Only an existing shelf with at least five units can supply the order.

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() {
	stock := []int{2, 5}
	for _, i := range []int{-1, 1, 2} {
		if i >= 0 && i < len(stock) && stock[i] >= 5 {
			fmt.Println("take")
		} else {
			fmt.Println("skip")
		}
	}
}
Output
skip
take
skip

Only index 1 is in bounds in the three trial lookups. Its value is exactly the threshold of 5, so it passes the inclusive comparison.

Try it yourself

Try index 0, then change its value from 2 to 5. How does its classification change?

Check your answer

Index 0 is valid in both cases. It changes from skip to take when its value reaches 5.

Go language specification

Related tags

  • Go
  • operators
  • short-circuit evaluation
  • bounds checks