Menu
Coddy logo textTech

Accessing Slice Elements

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

Accessing slice elements works just like arrays, using square brackets with an index position (starting from 0).

Create a slice of fruits:

fruits := []string{"Apple", "Banana", "Cherry"}
fmt.Println(fruits[0])  // First element
fmt.Println(fruits[1])  // Second element
fmt.Println(fruits[2])  // Third element

This displays:

Apple
Banana
Cherry

You can also modify elements by assigning new values:

fruits[1] = "Blueberry"
fmt.Println(fruits)

Result:

[Apple Blueberry Cherry]
challenge icon

Challenge

Beginner

In this challenge, you'll practice accessing elements from a slice in Go.

We've created a slice of fruits for you. Your task is to access specific elements from this slice and print them.

Cheat sheet

Access slice elements using square brackets with index position (starting from 0):

fruits := []string{"Apple", "Banana", "Cherry"}
fmt.Println(fruits[0])  // Apple
fmt.Println(fruits[1])  // Banana
fmt.Println(fruits[2])  // Cherry

Modify slice elements by assigning new values:

fruits[1] = "Blueberry"
fmt.Println(fruits)  // [Apple Blueberry Cherry]

Try it yourself

package main

import "fmt"

func main() {
	// A slice of fruits
	fruits := []string{"apple", "banana", "cherry", "date", "elderberry"}
	
	// TODO: Access the first fruit (index 0) and store it in a variable called firstFruit
	
	// TODO: Access the third fruit (index 2) and store it in a variable called thirdFruit
	
	// Print the results
	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