Menu
Coddy logo textTech

Iterating Over Slices

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

To iterate over a slice in Go, you can use a for loop with the range keyword.

Create a slice of fruits:

fruits := []string{"Apple", "Banana", "Cherry"}
fmt.Println("Fruits:", fruits)

Iterate through the slice using range:

for index, value := range fruits {
    fmt.Printf("Index: %d, Value: %s\n", index, value)
}

Result:

Fruits: [Apple Banana Cherry]
Index: 0, Value: Apple
Index: 1, Value: Banana
Index: 2, Value: Cherry

If you only need the values, use the blank identifier (_):

for _, fruit := range fruits {
    fmt.Println(fruit)
}
challenge icon

Challenge

Easy

In this challenge, you'll practice iterating over a slice of fruits using the range keyword. Your task is to loop through the slice and print each fruit with its position in the list.

The slice is already defined for you. You need to complete the for loop using range to iterate through the slice and print each fruit with its position (starting from 1).

Cheat sheet

To iterate over a slice in Go, use a for loop with the range keyword:

fruits := []string{"Apple", "Banana", "Cherry"}

for index, value := range fruits {
    fmt.Printf("Index: %d, Value: %s\n", index, value)
}

If you only need the values, use the blank identifier (_):

for _, fruit := range fruits {
    fmt.Println(fruit)
}

Try it yourself

package main

import "fmt"

func main() {
	// A slice of fruits
	fruits := []string{"Apple", "Banana", "Cherry", "Dragon fruit", "Elderberry"}
	
	// TODO: Complete the for loop using range to iterate through the fruits slice
	// Print each fruit with its position like: "1. Apple"
	
	for // Add your range loop here {
		// Add your code here to print each fruit with its position
		
	}
}
quiz iconTest yourself

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

All lessons in Fundamentals