We access array elements to get or use the specific values stored inside the array. This helps us work with individual pieces of data.
0
0
Accessing array elements in Go
Introduction
When you want to read a specific value from a list of items.
When you need to update or change a particular item in a collection.
When you want to loop through items and process each one.
When you want to compare or check a value at a certain position.
When you want to print or display a specific element from a group.
Syntax
Go
package main import "fmt" func main() { var numbers [5]int = [5]int{10, 20, 30, 40, 50} // Access element at index 2 value := numbers[2] fmt.Println(value) }
Array indexes start at 0, so the first element is at index 0.
Trying to access an index outside the array size causes a runtime panic.
Examples
Accessing first and last elements in a small array.
Go
package main import "fmt" func main() { var letters [3]string = [3]string{"a", "b", "c"} fmt.Println(letters[0]) // Output: a fmt.Println(letters[2]) // Output: c }
Example of an empty array with zero length.
Go
package main import "fmt" func main() { var emptyArray [0]int // No elements to access, accessing any index will cause panic fmt.Println(len(emptyArray)) // Output: 0 }
Accessing the only element in a single-element array.
Go
package main import "fmt" func main() { var singleElement [1]string = [1]string{"only"} fmt.Println(singleElement[0]) // Output: only }
Sample Program
This program shows how to access and update elements in an array. It prints the array before and after changing one element.
Go
package main import "fmt" func main() { // Create an array of 5 integers var scores [5]int = [5]int{85, 90, 78, 92, 88} // Print the whole array fmt.Println("Scores array:", scores) // Access and print the first element fmt.Println("First score:", scores[0]) // Access and print the last element fmt.Println("Last score:", scores[4]) // Change the third element scores[2] = 80 fmt.Println("Updated scores array:", scores) }
OutputSuccess
Important Notes
Accessing an element by index is very fast, it takes constant time O(1).
Arrays have fixed size, so you cannot access indexes outside their length.
Common mistake: forgetting that indexes start at 0, not 1.
Use arrays when you know the number of elements in advance and want fast access.
Summary
Arrays store multiple values of the same type in order.
You access elements using their index, starting at 0.
Accessing elements is fast and simple but be careful not to go out of bounds.