Course Content
Introduction to GoLang
Introduction to GoLang
Accessing and Modifying Array Elements
In the previous chapter, we learned how to declare and initialize an array. In this chapter, we will explore how to access and modify individual elements of an array.
Each element in the array is assigned an index that represents its position within the array. The first element of an array is assigned the index 0
, the second element has the index 1
, and so forth. It's important to note that when an array contains ten elements, the last element will have an index of 9
, as indexing starts from 0
.
Here is the syntax for referencing an element within an array:
Note
The process of accessing array elements by their indexes is referred to as indexing.
Let's revisit the students
array we discussed in the previous chapter. We can access its second element using indexing:
index
var students = [4] string { "Luna", "Max", "Ava", "Oliver" } fmt.Println(students[1]) // Output: Max
An array functions as a collection of variables. When we reference an element using indexing, we are essentially accessing a variable. Consequently, we can also modify it:
index
var students = [4] string { "Luna", "Max", "Ava", "Oliver" } fmt.Println(students) // Output: [Luna Max Ava Oliver] students[1] = "Tom" fmt.Println(students) // Output: [Luna Tom Ava Oliver]
Thanks for your feedback!