TheAlgorithms/Go · error
index out of bounds
Error message
index out of bounds
What it means
Set(row, col, val) returns this error when the target coordinates are outside the matrix (negative or >= row/column count). The matrix is left unmodified. Note the message differs slightly from Get's ("out of bounds" vs "out of range").
Source
Thrown at math/matrix/matrix.go:76
for i := range matrix.elements {
matrix.elements[i] = make([]T, columns)
copy(matrix.elements[i], elements[i])
}
return matrix, nil
}
func (m Matrix[T]) Get(row, col int) (T, error) {
if row < 0 || row >= m.rows || col < 0 || col >= m.columns {
var zeroVal T
return zeroVal, errors.New("index out of range")
}
return m.elements[row][col], nil
}
func (m Matrix[T]) Set(row, col int, val T) error {
if row < 0 || row >= m.rows || col < 0 || col >= m.columns {
return errors.New("index out of bounds")
}
m.elements[row][col] = val
return nil
}
func (m Matrix[T]) Rows() int {
return len(m.elements)
}
func (m Matrix[T]) Columns() int {
if len(m.elements) == 0 {
return 0
}
return len(m.elements[0])
}
View on GitHub (pinned to 5ba447ec5f)
Solutions
- Validate 0 <= row < m.Rows() and 0 <= col < m.Columns() before Set.
- Correct loop bounds (use i < rows, j < cols) and argument order.
- Re-create the matrix with New(rows, cols, zero) if it is smaller than needed.
Example fix
// before
for i := 0; i <= 3; i++ { m.Set(i, 0, v) } // errors at i == 3
// after
for i := 0; i < m.Rows(); i++ { m.Set(i, 0, v) } Defensive patterns
Strategy: validation
Validate before calling
if r < 0 || r >= m.Rows() || c < 0 || c >= m.Columns() {
return fmt.Errorf("cannot set (%d,%d) on %dx%d matrix", r, c, m.Rows(), m.Columns())
}
err := m.Set(r, c, v) Type guard
func canSet[T constraints.Integer](m math.Matrix[T], row, col int) bool {
return row >= 0 && row < m.Rows() && col >= 0 && col < m.Columns()
} Try / catch
if err := m.Set(r, c, v); err != nil {
return fmt.Errorf("set(%d,%d) failed: %w", r, c, err)
} Prevention
- Bound fill loops with i < m.Rows(), j < m.Columns().
- Reuse the same guard helper for Get and Set.
- Re-create the matrix with New() when a larger canvas is needed instead of writing out of bounds.
When it happens
Trigger: Calling Set with row >= m.rows, col >= m.columns, or negative values — e.g. Set(1,3,v) on a 3-column matrix, or any Set on an empty 0x0 matrix.
Common situations: Off-by-one fill loops (i <= size), writing to coordinates computed from another (larger) matrix, 1-based index habits, resizing logic that shrank the matrix but not the loop.
Related errors
- index out of range
- submatrix dimensions exceed matrix bounds
- Matrix rows and columns must equal in order to find the dete
- rows have different numbers of columns
- matrices cannot be multiplied: column count of the first mat
AI-assisted analysis of TheAlgorithms/Go@5ba447ec5f (2026-09-02).
Data as JSON: /api/errors/c16ebce130e86ad4.
Report an issue: GitHub.