Hello everyone, In this tutorial, we will show you simple range example in Go language. The example program has been tested and shared in the post.

Syntax

for index, element := range someSlice {
..........
.........
}

Iterating an Array using Range in Go

package main
import "fmt"
func main() {
// creating an array
var names = []string{"Dinesh", "Krishnan", "John", "Smith", "Robert"}
fmt.Println("Iterating using Traditional For-Loop")
// iterating an array using traditional for-loop
for i := 0; i < len(names); i++ {
fmt.Println(names[i])
}
fmt.Println()
fmt.Println("Iterating using Range")
// iterating an array using range
for _, element := range names {
println(element)
}
}

Output

Iterating using Traditional For-Loop
Dinesh
Krishnan
John
Smith
Robert
Iterating using Range
Dinesh
Krishnan
John
Smith
Robert

References

  1. https://golang.org/doc/
  2. https://golang.org/pkg/
  3. https://golang.org/pkg/fmt/
  4. https://golang.org/pkg/fmt/#Println
  5. https://golang.org/ref/spec#For_statements
  6. https://stackoverflow.com/questions/7782411/is-there-a-foreach-loop-in-go

Tags:

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *