×

Go Tutorial

Go Basics

Go Variables

Go Literals

Go Type Handling

Go Operators

Go Decision Making

Go Loops

Go Functions

Go String

Go Arrays

Go Slices

Go Maps

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Go - Iterate Over a Slice

Last Updated : May 17, 2025

You can iterate over a slice using a for loop in two common ways:

  • Using a simple for loop with an index.
  • Using a for range loop.

Iterate Over a Slice Using Index

You can use a for loop with an index to access each element by its position.

Example

In this example, we are iterating over a slice of Indian cities using an index-based loop:

package main
import "fmt"

func main() {
    cities := []string{"Delhi", "Mumbai", "Kolkata"}

    for i := 0; i < len(cities); i++ {
        fmt.Printf("City at index %d is %s\n", i, cities[i])
    }
}

When executed, this program outputs:

City at index 0 is Delhi
City at index 1 is Mumbai
City at index 2 is Kolkata

Iterate Over a Slice Using for range

The for range loop provides a simple way to iterate over slices. It returns both the index and the value for each element.

Example

In this example, we are iterating over the same slice of Indian cities using for range:

package main
import "fmt"

func main() {
    cities := []string{"Delhi", "Mumbai", "Kolkata"}

    for index, city := range cities {
        fmt.Printf("City at index %d is %s\n", index, city)
    }
}

When executed, this program outputs:

City at index 0 is Delhi
City at index 1 is Mumbai
City at index 2 is Kolkata

Iterate Over a Slice by Ignoring Index or Value

If you only need the index or only the value, you can ignore the other by using the blank identifier _.

Example

In this example, we are printing only the city names from the slice, ignoring the index:

package main
import "fmt"

func main() {
    cities := []string{"Delhi", "Mumbai", "Kolkata"}

    for _, city := range cities {
        fmt.Println(city)
    }
}

When executed, this program outputs:

Delhi
Mumbai
Kolkata

Exercise

Select the correct option to complete each statement about iterating over a slice in Go.

  1. The keyword used to get both index and value while iterating over a slice is ___.
  2. To ignore the index when iterating using for range, you use ___.
  3. What is the output of the following code snippet?

    In this example, we are printing only the first city in the slice:

    cities := []string{"Chennai", "Hyderabad"}
    for i, city := range cities {
        if i == 0 {
            fmt.Println(city)
        }
    }
            

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.