Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

Go: Different ways of iterating over an Array and Slice

Posted on October 20, 2023November 12, 2023 by admin

Go provides many different ways of iterating over an array. All examples below are also applicable to slice.

Let’s define an array of letters first

letters := []string{"a", "b", "c", "d", "e"}

Table of Contents

  • Using the range operator
  • Using Only For operator

Using the range operator

  • With index and value
for i, letter := range letters {
fmt.Printf("%d %s\n", i, letter)
}
  • Only Value
for _, letter := range letters {
fmt.Println(letter)
}
  • Only index
for i := range letters {
fmt.Println(i)
}
  • Without value and index. Just print array values
i := 0
for range letters {
fmt.Println(i)
i++
}

Using Only For operator

  • Single initialization and post
len := len(letters)
for i := 0; i < len; i++ {
fmt.Println(letters[i])
}
  • Multiple initialization and post statement
len := len(letters)
for i, j := 0, len; i < j; i, j = i+1, j-1 {
fmt.Println(letters[i])
}
  • array
  • go
  • golang
  • iterating
  • iteration
  • slice
  • Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2023 Welcome To Golang By Example | Design: Web XP