Go Slice bounds check
A slice index must be within its current length. Check a saved position before indexing.
A simple example
Slice bounds check
- Start with A list containing only A
- Do this Ask for the third item
- Result Outside the list
Syntax
index >= 0 && index < len(seats)
Run these examples in Go
Save one example at a time as main.go. Use Go 1.21 or later.
go run main.goFind a seat after the coach changes
A bus operator replaces a coach with a smaller one. A passenger's saved seat position now falls outside the new seating list, so the booking screen must ask them to choose again.
package main
import (
"fmt"
)
func main() {
seats := []string{"Window", "Aisle"}
index := 2
if index < 0 || index >= len(seats) {
fmt.Println("Choose another seat")
} else {
fmt.Println(seats[index])
}
}
Choose another seat
The saved position is just beyond the two-seat list. The booking desk asks for a replacement seat.
Open the last appointment
A desk offers two appointments and a visitor selects index one. Look up the zero-based slot. Ask the user to choose again if that position falls outside the available list.
Reject a stale bus selection
An old menu points to index two after the coach list shrinks to two stops. Look up the zero-based slot. Ask the user to choose again if that position falls outside the available list.
What to watch for
The slice capacity can exceed its length. The length determines which elements are available.