Fix Go "panic: runtime error: slice bounds out of range" — A High Bound Past Capacity, a Low Bound Past the High Bound, a Full Slice Expression Past Capacity, a String Past Its Length, and a Negative Bound
This panic means a slice expression asked for a range the value does not have: a high bound past the end, a low bound past the high bound, a capacity limit past the capacity, or a bound below zero. Each section below takes one shape — the high bound judged against capacity rather than length, the legal extension up to capacity that the same rule allows, the reversed bounds, the three-index form, the string form judged against its length in bytes, and the negative bound in its run-time and compile-time forms — shows the exact output it prints, and gives the check that keeps the bounds inside the rule before the expression runs.
Written November 21, 2026 · Tested with Go 1.26.4 · 9 min read
- The first failure: a high bound past capacity
- The legal case the same rule allows: extending a slice up to its capacity
- The reversed bounds: a low bound greater than the high bound
- The full slice expression: the third bound is judged against capacity
What this guide is
panic: runtime error: slice bounds out of range is a run-time panic: the program built, started, and then evaluated a slice expression whose bounds are out of range. The specification states the rule separately for the two forms of slice expression. For a simple slice expression a[low:high] on an array or a string, the indices are in range if 0 <= low <= high <= len(a). For a slice operand the upper index bound is the slice capacity cap(a) rather than the length, so the same form on a slice is in range if 0 <= low <= high <= cap(a). For a full slice expression a[low:high:max], available for arrays and slices but not strings, the indices are in range if 0 <= low <= high <= max <= cap(a). In every form, if the indices are out of range at run time, a run-time panic occurs — and the panic text tells you which comparison failed, because it prints the bounds that were used and the capacity or length they were judged against.
That last point is what separates this panic from its sibling, the index out of range panic. An index names one element and is judged against a length. A slice expression names a range and, for a slice operand, is judged against a capacity — which is why a high bound larger than the length can be entirely legal, as the second program in this guide shows. The capacity of a slice is the number of elements for which there is space allocated in the underlying array, and 0 <= len(s) <= cap(s) holds at all times, so length and capacity are the same number only when the slice fills its array. Most of the shapes in this guide come from code that computed a bound from one value and applied it to another: a page size against a shorter result set, a window end against a slice that was re-sliced smaller, a byte count against a string. The expression in the trace is where the panic fires. The defect is wherever the bound and the value stopped agreeing.
The examples here use Go 1.26.4. Every example lives in a single file named main.go inside one module, created once from an empty directory:
$ mkdir slicebounds
$ cd slicebounds
$ go mod init example.com/slicebounds
go: creating new go.mod: module example.com/slicebounds
Each program that follows replaces the contents of that main.go. The panic transcripts are shown as printed by go run -trimpath main.go: the -trimpath flag only changes how file positions print in the trace — ./main.go:8 here, where a plain run prints the same line number behind the full directory path on your machine. Tested with Go 1.26.4.
The first failure: a high bound past capacity
The smallest program that earns the panic slices a three-element slice up to a bound of five:
// main.go
package main
import "fmt"
func main() {
s := []int{10, 20, 30}
hi := 5
fmt.Println(s[:hi])
fmt.Println("after")
}
$ go run -trimpath main.go
panic: runtime error: slice bounds out of range [:5] with capacity 3
goroutine 1 [running]:
main.main()
./main.go:8 +0x36
exit status 2
The slice literal gives the slice a length of 3 and a capacity of 3 — a slice literal's capacity reaches exactly the elements it holds — so the bound 5 is past both. The message prints the expression in the form [:5], with the omitted low bound left empty, and names the limit it was judged against: with capacity 3, not with length 3, even though the two are equal here. Read that wording literally. When the message says capacity, the operand is a slice and the comparison that failed is high <= cap(s). When it says length, as the string program below does, the operand is an array or a string and the comparison is high <= len(a). The compiler accepts this program because hi is a variable: its value is a run-time fact, and the check belongs to the run. At the expression on line 8 the bound is past the capacity, the runtime raises the panic, and the after line never prints.
In working code the bound is rarely a literal five against a literal three. It is an end offset computed from a request, a chunk size added to a start position, or a count taken from a different collection than the one being sliced. The shape is the same in each case: a bound that is usually inside the capacity reaches the expression on the one run where the value is smaller than the arithmetic assumed, and nothing between the computation and the expression tested the pair together.
The legal case the same rule allows: extending a slice up to its capacity
Before fixing anything, meet the case that looks identical and is not a defect at all. A slice made with spare capacity can be re-sliced past its length, up to its capacity:
// main.go
package main
import "fmt"
func main() {
s := make([]int, 3, 5)
s[0], s[1], s[2] = 10, 20, 30
fmt.Println(s[:5], len(s[:5]), cap(s[:5]))
}
$ go run -trimpath main.go
[10 20 30 0 0] 5 5
The program runs clean. make([]int, 3, 5) builds a slice of length 3 in an array of 5, the expression s[:5] extends it over the two spare elements — which hold the zero value, because the underlying array was allocated and zeroed — and the result has length 5 and capacity 5. Slicing does not copy the slice's data: it creates a new slice value that points to the original array, which is what makes this extension possible at all. This is the deliberate mechanism behind growing a slice within its capacity, and it is why the simple-form rule for slices names capacity rather than length.
The practical consequence cuts both ways. Code that clamps a high bound to len(s) when the intent was to use the spare capacity throws away a legal range. Code that assumes the bound only needs to beat the length — written against an array mental model — panics the first time the slice's capacity equals its length, which is the common case for slice literals and for the result of most conversions. The check that matches the rule tests the bound against the same limit the runtime tests: cap for a slice operand in the simple form, len for an array or a string.
The reversed bounds: a low bound greater than the high bound
A slice expression can fail with both bounds inside the value, if they are in the wrong order:
// main.go
package main
import "fmt"
func main() {
s := []int{10, 20, 30}
lo, hi := 3, 1
fmt.Println(s[lo:hi])
fmt.Println("after")
}
$ go run -trimpath main.go
panic: runtime error: slice bounds out of range [3:1]
goroutine 1 [running]:
main.main()
./main.go:8 +0x36
exit status 2
This message names no capacity and no length, because no limit was crossed: 3 and 1 are each inside the slice, and the comparison that failed is the middle one, low <= high. A slice expression selects the elements from low up to but not including high, and its result has length high - low; a reversed pair would give that length a negative value, which no slice can have. The defect in real code is almost never two literals typed in the wrong order. It is two computed bounds — a start derived from one position and an end derived from another — meeting on an input where the start has moved past the end: an empty region, a search that found its marker before its start marker, a window whose end was clamped and whose start was not. A guard that tests each bound against the capacity separately passes this shape, because each bound passes alone. The check has to test the pair: low <= high, alongside the two limit comparisons.
The full slice expression: the third bound is judged against capacity
The three-index form adds a third bound that sets the result's capacity, and that bound has its own place in the rule:
// main.go
package main
import "fmt"
func main() {
s := []int{10, 20, 30}
max := 5
fmt.Println(s[0:2:max])
fmt.Println("after")
}
$ go run -trimpath main.go
panic: runtime error: slice bounds out of range [::5] with capacity 3
goroutine 1 [running]:
main.main()
./main.go:8 +0x36
exit status 2
The expression s[low:high:max] constructs a slice with the same length and elements as s[low:high] and additionally controls the resulting slice's capacity by setting it to max - low. The rule for the form is 0 <= low <= high <= max <= cap(a), and here the first two bounds are legal — the length-2 result exists — while max at 5 is past the capacity of 3, so the expression panics before any result is produced. The message prints the failing bound in the third position with the first two left empty, [::5], and again names the capacity it was judged against. The three-index form exists to cap a result so that a later append to it allocates a new array instead of writing into the shared one; the max in real code is usually copied from the high bound of a neighbouring expression or computed from a size the operand no longer has. The check for this form has four comparisons, not three: the chain only holds if max also sits inside the capacity.
The string form: bounds are byte positions, judged against the length
Strings take the simple form only, and their limit is the length:
// main.go
package main
import "fmt"
func main() {
t := "hello"
hi := 8
fmt.Println(t[:hi])
fmt.Println("after")
}
$ go run -trimpath main.go
panic: runtime error: slice bounds out of range [:8] with length 5
goroutine 1 [running]:
main.main()
./main.go:8 +0x9
exit status 2
A slice expression on a string constructs a substring, and its indices are in range if 0 <= low <= high <= len(t). The message says with length 5 where the slice programs said with capacity: a string has no capacity to extend into, so there is no legal version of this expression past 5. The length of a string is its length in bytes — len on a string type returns the string length in bytes — so the bounds of a string slice expression are byte positions, not character positions. A bound computed by counting characters in text that contains multi-byte characters undershoots or overshoots the byte positions the expression needs, and a bound that lands between the bytes of one character is legal as far as this rule is concerned: it produces a substring holding a partial character rather than panicking. Both failure styles trace back to the same mismatch — a bound produced in one unit applied in another — and the check that prevents the panic is a comparison of the bounds against len(t) in bytes, done at the expression.
The negative bound: a panic from a variable, a compile error from a constant
The low end of the rule, 0 <= low, fails in two different ways depending on how the negative value reaches the expression. As a variable, it panics:
// main.go
package main
import "fmt"
func main() {
s := []int{10, 20, 30}
lo := -1
fmt.Println(s[lo:])
fmt.Println("after")
}
$ go run -trimpath main.go
panic: runtime error: slice bounds out of range [-1:]
goroutine 1 [running]:
main.main()
./main.go:8 +0x3d
exit status 2
The message prints the bound in the low position, [-1:], and names no limit, because the comparison that failed is the first one in the chain. Negative bounds arrive in real code from arithmetic: an index minus a radius, a start position minus a look-back count, a length minus a size — each correct on ordinary inputs and negative exactly when the input is smaller than the offset. Slices cannot be re-sliced below zero to access earlier elements in the array; there is nothing before the start to reach.
Write the same bound as a constant and the program never runs:
// main.go
package main
import "fmt"
func main() {
s := []int{10, 20, 30}
fmt.Println(s[-1:])
}
$ go run -trimpath main.go
# command-line-arguments
./main.go:7:16: invalid argument: index -1 (constant of type int) must not be negative
This is a compile error, not a panic: no goroutine trace, no exit status line, just the position and the message. The specification requires a constant index to be non-negative, so the compiler, which evaluates the constant while it builds the program, rejects the code itself. The contrast is the diagnostic value of the pair. A negative bound reported by the compiler means the value was visible in the source, and the fix is to correct the expression. The run-time panic means the negative arrived in a variable, and the fix is a check that the computed bound is still at least zero before the expression runs — the same split, between source-visible and run-time values, that decides every shape in this guide.
The fixed program
One program that applies the checks at once: a window function that tests the full chain for the simple form — non-negative low bound, ordered bounds, high bound inside the capacity — and returns the failure as an error instead of panicking:
// main.go
package main
import (
"errors"
"fmt"
)
func window(s []int, lo, hi int) ([]int, error) {
if lo < 0 || hi < lo || hi > cap(s) {
return nil, errors.New("slice bounds out of range")
}
return s[lo:hi], nil
}
func main() {
s := make([]int, 3, 5)
s[0], s[1], s[2] = 10, 20, 30
w, err := window(s, 0, 5)
fmt.Println(w, err)
w, err = window(s, 0, 8)
fmt.Println(w, err)
w, err = window(s, 3, 1)
fmt.Println(w, err)
w, err = window(s, -1, 2)
fmt.Println(w, err)
}
$ go run main.go
[10 20 30 0 0] <nil>
[] slice bounds out of range
[] slice bounds out of range
[] slice bounds out of range
The first call is the legal extension from earlier in the guide: bounds 0 and 5 against a capacity of 5 pass the chain, and the result is the length-5 slice including the two zero-valued spare elements. Each of the next three calls breaks a different comparison — a high bound of 8 past the capacity, a low bound of 3 past a high bound of 1, a low bound of -1 below zero — and each returns the same error value with a nil slice, which prints as [], instead of stopping the program. The guard tests the bounds against cap(s) because the function's contract is the simple slice form on a slice; a caller that wants the result confined to the elements the slice currently holds tests against len(s) instead, and that is a decision about what the function promises, made once in the function rather than rediscovered at each call site. Nothing in the program clamps a bound silently: a clamped window returns elements the caller did not ask for, where the error names the actual defect, a pair of bounds that do not fit the value they were applied to.
The fixes, ranked
Test the whole chain at the expression, and return the failure as a value. For the simple form on a slice the chain is 0 <= low, low <= high, and high <= cap(s); for an array or a string the last comparison is against len(a); for the full form add high <= max and max <= cap(a). A function that slices by computed bounds tests the chain first and returns an error, or a presence flag, when any link fails. This is ranked first because it covers every caller, tests the bounds against the same limit the runtime tests, and turns a panic that unwinds the program into a value the caller already has to handle.
Decide whether the limit is the length or the capacity, and write that limit. Extending a slice into its spare capacity is legal and sometimes the point of the code; confining a window to the current elements is also a legitimate contract. The two contracts have different checks, cap and len, and confusing them produces both failure styles in this guide: panics from a capacity assumption on a full slice, and silently discarded range from a length clamp on a slice with spare capacity. The limit belongs in the owning function's check, named once.
Test the bounds as a pair, not one at a time. The reversed-bounds shape passes every per-bound limit test and still panics, because the failing comparison is between the bounds themselves. Any check that validates low and high separately without comparing them leaves that shape in place.
Check computed bounds where the arithmetic can go negative. A bound built by subtraction — an index minus a radius, a length minus a size — needs its non-negativity established after the subtraction, at the expression or at the computation. Testing the inputs to the subtraction does not establish it, because each input can be ordinary while the difference is negative.
Compute string bounds in bytes. String slice bounds are byte positions judged against the length in bytes. A bound counted in characters, or taken from a different string, needs converting or re-deriving in bytes before the expression — and a bound that must land on a character boundary needs that stronger condition checked separately, because the bounds rule alone permits a cut through a multi-byte character.
Do not answer the panic by clamping silently or by recovering around your own slicing. A clamp returns a window of a size the caller did not request, and the defect travels on as wrong data. A recover around the program's own expressions converts a missing check into an unwinding and leaves the bad bound free to arrive again on the next call. Both have their place at boundaries around work the program does not control; the check is the fix at the expression the program owns.
Which fix for which cause
| What the message and code show | Cause | Fix |
|---|---|---|
slice bounds out of range [:5] with capacity 3 at a simple slice expression |
The high bound is past the slice's capacity | Test high <= cap(s) at the expression; return an error when it fails |
| No panic, and a slice expression's high bound is past the length but inside the capacity | The extension into spare capacity is the legal simple-form case for slices | No fix needed; if the contract is the current elements only, test against len(s) deliberately |
slice bounds out of range [3:1], with no capacity or length named |
The low bound is greater than the high bound | Test the bounds as a pair, low <= high, alongside the limit comparisons |
slice bounds out of range [::5] with capacity 3 at a three-index expression |
The max bound is past the capacity |
Test the full chain 0 <= low <= high <= max <= cap(a) |
slice bounds out of range [:8] with length 5 at a string expression |
The high bound is past the string's length in bytes | Test the bounds against len(t) in bytes at the expression |
slice bounds out of range [-1:] |
A computed low bound went negative at run time | Test the bound after the arithmetic that produced it, 0 <= low |
invalid argument: index -1 (constant of type int) must not be negative from the compiler, with a position instead of a trace |
The bound is a negative constant, visible in the source | Correct the constant expression in the source |
Checklist
- Read the panic text before the code: the bracket form shows which bounds were present, and the words after it — capacity, length, or neither — name the comparison that failed.
- For every slice expression with a computed bound, name the limit the runtime uses: capacity for a slice operand, length for an array or a string, and
max <= capadded for the full form. - Confirm each check tests the whole chain, including the pair comparison
low <= high— per-bound tests alone leave the reversed shape in place. - Follow each bound back to its computation: a count from another collection, an offset added to a start, a subtraction that can go negative. The check belongs at the expression and, where the bound is produced for several expressions, at its source too.
- Test the empty and the full cases: a zero-length slice, a slice whose capacity equals its length, and a slice with spare capacity whose extension is or is not intended.
- Where strings are sliced, confirm the bounds were computed in bytes against this string's length, and that any cut that must respect character boundaries checks that condition separately.
Related guides on this site
- Fix Go "panic: runtime error: index out of range" — Slice, Array, String, and Slice-Bounds Panics — the sibling runtime panic judged against a length: its message names the single index and the length it crossed, where this guide's expressions name a pair of bounds and, for slices, the capacity they were judged against.
- Go Slices and Maps — Append, Length, Capacity, and Lookup — the length and capacity model this guide's rule rests on: how a slice's length and capacity are set at creation, how
appendgrows past the capacity, and why the two numbers differ. - Fix Go "panic: runtime error: integer divide by zero" — Variable Divisors, the Constant-Divisor Compile Error, Modulo, and the Empty Average — the same source-visible versus run-time split in another panic family: a constant zero divisor is a compile error, a variable one is a panic, where here a constant negative bound is the compile error and a computed one is the panic.
Sources
- The Go Programming Language, The Go Programming Language Specification — for slice expressions (the simple form constructs a substring or slice; for arrays or strings the indices are in range if
0 <= low <= high <= len(a); for slices the upper index bound is the slice capacitycap(a)rather than the length; a constant index must be non-negative; out-of-range indices at run time cause a run-time panic), for full slice expressions (the third bound sets the result's capacity tomax - low, and the indices are in range if0 <= low <= high <= max <= cap(a)), and for length and capacity (lenon a string type is the string length in bytes, the capacity of a slice is the number of elements for which there is space allocated in the underlying array, and0 <= len(s) <= cap(s)holds at all times). - The Go Programming Language, Go Slices: usage and internals — for the slice model behind the capacity rule (a slice is a descriptor of an array segment consisting of a pointer to the array, the length of the segment, and its capacity; slicing does not copy the slice's data; a slice can be grown to its capacity by slicing it again; a slice cannot be grown beyond its capacity and attempting to do so causes a runtime panic; slices cannot be re-sliced below zero).
Keep Exploring
The full Go hub \u2014 slices and maps, concurrency, and the standard library.
Every guide on the site in one list, grouped by topic.
Every browser-only checker and verifier on the site.
The C++, Python, Sysadmin, Rust, Go, and TypeScript hubs.