Accessing Array Elements
Start with Accessing Array Elements
Array elements are accessed with zero-based indexes. The first position is index 0 and the last is length minus one.
What you’ll learn
- Explain the main purpose of accessing array elements.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
For colors := [3]string{"red", "blue", "green"}, colors[0] is red and colors[2] is green. Use len(colors) to discover the number of elements rather than hard-coding the end index.
Accessing an index outside the valid range fails: a constant invalid index is usually rejected by the compiler, while an invalid index computed at runtime causes a panic. Check indexes before accessing data derived from input.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func main() {
colors := [3]string{"red", "blue", "green"}
fmt.Println("First:", colors[0])
fmt.Println("Last:", colors[len(colors)-1])
index := 1
if index >= 0 && index < len(colors) {
fmt.Println("Selected:", colors[index])
}
}
Output
First: red
Last: green
Selected: blueTrace what the program does
The array has indexes 0, 1 and 2. Its length is 3, so len(colors)-1 selects index 2. The conditional check confirms index 1 is valid before reading the middle element.
Avoid common mistakes
- Do not assume indexes begin at 1; the first element is index 0.
- Check bounds before using an index computed from untrusted or changing data.
Try it yourself
Change the index variable to 4 and verify the bounds check prevents an invalid access. Then test index 0.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Accessing Array Elements in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.