GoLang - Accessing Elements from Array

In this tutorial, we will learn how to access specific element from an array by using index position along with the working examples of it.

In Golang, It can be possible to access particular element from an array by using index position.Indexing starts from 0.

Syntax:

array_name[index_pos]

Where, index_pos is the index.

Array Access Elements:

Example 1:

Let us create an array with integer type that holds 5 values and access some of them.

CopiedCopy Code

package main
import ("fmt")

func main() {
    // Declare an array that hold 5 integers
   first := [...]int{34,56,53,67,65}
   
// Display array
 fmt.Println("Actual Array: ",first)
 
 // Get 4th element.
 fmt.Println("Index-3:",first[3])
 
 // Get 5th element.
 fmt.Println("Index-4:",first[4])
 
 // Get 1st element.
 fmt.Println("Index-0:",first[0])
}

Output:

CopiedCopy Code

Actual Array:  [34 56 53 67 65]
Index-3: 67
Index-4: 65
Index-0: 34

Explanation for the above output:

We accessed elements present at index-3,4 and 0 separately.

Example 2:

Let us create an array with string type that holds 5 strings and access some of them.

CopiedCopy Code

package main
import ("fmt")

func main() {
    // Declare an array that hold 5 strings
   first := [...]string{"Welcome","to","GKINDEX","GO","Language"}
   
// Display array
 fmt.Println("Actual Array: ",first)
 
 // Get 4th element.
 fmt.Println("Index-3:",first[3])
 
 // Get 5th element.
 fmt.Println("Index-4:",first[4])
 
 // Get 1st element.
 fmt.Println("Index-0:",first[0])
}

Output:

CopiedCopy Code

Actual Array:  [Welcome to GKINDEX GO Language]
Index-3: GO
Index-4: Language
Index-0: Welcome

Explanation for the above output:

We accessed elements present at index-3,4 and 0 separately.

Example 3:

Let us create an array of length-5 with integer type that holds 2 integers and access some of them.

CopiedCopy Code

package main
import ("fmt")

func main() {
    // Declare an array that hold integers of length-5
   first := [5]int{1:34,4:56}
   
// Display array
 fmt.Println("Actual Array: ",first)
 
 // Get 4th element.
 fmt.Println("Index-3:",first[3])
 
 // Get 5th element.
 fmt.Println("Index-4:",first[4])
 
 // Get 1st element.
 fmt.Println("Index-0:",first[0])
}

Output:

CopiedCopy Code

Actual Array:  [0 34 0 0 56]
Index-3: 0
Index-4: 56
Index-0: 0

Explanation for the above output:

We accessed elements present at index-3,4 and 0 separately. Here we added only two elements in the array. Hence remaining three elements are set to 0.

Conclusion

Now we know how access the elements from the Array in a Golang and understood the implementation with working examples.