Skip to main content

How to Get an Element from a Slice by Its Index in Go

· 4 min read
Jagdish Kumawat
Founder @ Dewiride

Each element of a Go slice has a position, its index, and you read an element by putting its index in square brackets after the slice. Counting starts at 0, so colors[0] is the first element and colors[len(colors)-1] the last.

Syntax​

Syntax
<element> := <slice>[<index>]
<count> := len(<slice>)
PartWhat it does
<slice>[<index>]The element at <index>, counting from 0.
len(<slice>)How many elements the slice has. The last index is one less.

The Go language specification on index expressions says the index x is in range if 0 <= x < len(a), otherwise it is out of range, and: "if x is out of range at run time, a run-time panic occurs".

The Example​

The example reads the first and the third of three colors, the last one with len(colors)-1, the slice's length, and then the element at index 3, held in a variable.

Prerequisites​

  • Go. go run compiles and runs a single file. This guide uses Go 1.27.4.

Step 1: Write the Code​

Create a file named main.go:

main.go, which creates the slice red, green, blue and prints colors at 0, at 2, at len minus 1, len of colors, and colors at a variable i set to 3.

main.go
package main

import "fmt"

func main() {
colors := []string{"red", "green", "blue"}

fmt.Println(colors[0])
fmt.Println(colors[2])
fmt.Println(colors[len(colors)-1])
fmt.Println(len(colors))

i := 3
fmt.Println(colors[i])
}

Step 2: Run It​

Terminal
go run main.go
Output
red
blue
blue
3
panic: runtime error: index out of range [3] with length 3

goroutine 1 [running]:
main.main()
/Users/Shared/you/main.go:14 +0x130
exit status 2

A zsh terminal where go run main.go prints red, blue, blue and 3, then panic: runtime error: index out of range [3] with length 3, the goroutine trace and exit status 2.

The command is the same in zsh, bash and PowerShell.

What Happened​

  • colors[0] is the first element and colors[2] the third, because counting starts at 0.
  • colors[len(colors)-1] worked out the last index, 2.
  • colors[i] with i set to 3 asked for a fourth element. Go found that out while the program ran and stopped it with a panic that names the index and the length. go run then printed exit status 2.

Common Mistakes​

MistakeWhat happensDo this instead
Using colors[len(colors)] for the last elementIt's one past the end: a panicUse colors[len(colors)-1]
Using a negative index, as in colors[-1]It doesn't compile: invalid argument: index -1 (constant of type int) must not be negativeCount from the end with len(colors)-1
Indexing an empty slicecolors[0] panics when the slice has no elementsCheck len(colors) > 0 first

Troubleshooting​

SymptomLikely causeFix
panic: runtime error: index out of range [N] with length MThe index isn't below the lengthCheck len before indexing
exit status 2 after a panicgo run reports the program's exit codeFix the panic above it

FAQ​

Why did Go not catch colors[3] when compiling?​

A slice's length is only known when the program runs, and the index here came from a variable. Go checks constant indexes against arrays at compile time, but a slice index is checked at run time.

Can I change an element by its index?​

Yes: colors[1] = "yellow" replaces the second element.

Conclusion​

slice[index] reads an element, counting from 0, and len(slice) tells you how many there are. An index outside 0 to len - 1 panics at run time, so check the length when the index comes from data.

Additional Resources​