Menu
Coddy logo textTech

Accessing Array Elements

Part of the Fundamentals section of Coddy's GO journey — lesson 70 of 109.

To access array elements, use square brackets with an index number. Array indices start at 0.

Create an array of names:

names := [3]string{"Alex", "Beth", "Carlos"}

Access individual elements:

firstPerson := names[0]
secondPerson := names[1]
fmt.Println(firstPerson)
fmt.Println(secondPerson)

This displays:

Alex
Beth

You can also modify elements:

names[2] = "Charlie"
fmt.Println(names[2])

This outputs:

Charlie
challenge icon

Challenge

Beginner
In this challenge, you'll practice accessing elements from an array in Go. We've created an array of fruits, and your task is to access specific elements and print them.

Complete the code to:
1. Access the first fruit in the array
2. Access the third fruit in the array
3. Print both fruits using fmt.Println

Cheat sheet

To access array elements, use square brackets with an index number. Array indices start at 0.

Create an array:

names := [3]string{"Alex", "Beth", "Carlos"}

Access individual elements:

firstPerson := names[0]
secondPerson := names[1]

Modify elements:

names[2] = "Charlie"

Try it yourself

package main

import "fmt"

func main() {
    // This is our array of fruits
    fruits := [5]string{"apple", "banana", "cherry", "date", "elderberry"}
    
    // TODO: Create a variable called firstFruit and assign it the first element of the fruits array
    
    // TODO: Create a variable called thirdFruit and assign it the third element of the fruits array
    
    // Print the fruits
    fmt.Println("The first fruit is:", firstFruit)
    fmt.Println("The third fruit is:", thirdFruit)
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals