iterating Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/iterating/ Tue, 12 Nov 2019 18:58:32 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.1 https://i0.wp.com/golangbyexamples.com/wp-content/uploads/2021/05/cropped-go_border-1.png?fit=32%2C32&ssl=1 iterating Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/iterating/ 32 32 159787465 Go: Different ways of iterating over an Array and Slice https://vikasboss.github.io/go-different-ways-iterating-array-slice/ https://vikasboss.github.io/go-different-ways-iterating-array-slice/#respond Sun, 20 Oct 2019 07:20:42 +0000 https://vikasboss.github.io/?p=318 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 Using the range operator With index and...

The post Go: Different ways of iterating over an Array and Slice appeared first on Welcome To Golang By Example.

]]>
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"}

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])
}

The post Go: Different ways of iterating over an Array and Slice appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/go-different-ways-iterating-array-slice/feed/ 0 318