How to use range in Golang?

Member

by isadore , in category: Golang , 2 years ago

I have an array of integers defined and I usually use for loop to iterate over an array. I am not sure how is range function works and how can I replace this for loop with a range instead in Golang.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
package main

import "fmt"

func main() {
   arr := [4]int{1, 2, 3, 4}

   for i := 0; i < len(arr); i++ {
      fmt.Println(arr[i])
   }
}


Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by emma , 2 years ago

@isadore you can rewrite your for loop with a range like the below in Golang:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
package main

import "fmt"

func main() {
   arr := [4]int{1, 2, 3, 4}

   for key, val := range arr {
      fmt.Println("Key:", key)
      fmt.Println("Value:", val)
   }
   // Output:
   //Key: 0
   //Value: 1
   //Key: 1
   //Value: 2
   //Key: 2
   //Value: 3
   //Key: 3
   //Value: 4
}
by moriah.medhurst , 7 months ago

@isadore 

The range function in Golang can be used to iterate over an array, slice, or map. It returns both the index and the value at that index.


To replace your for loop with a range, you can modify your code as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
package main

import "fmt"

func main() {
   arr := [4]int{1, 2, 3, 4}

   for key, val := range arr {
      fmt.Println("Key:", key)
      fmt.Println("Value:", val)
   }
}


In the above code, the for loop is replaced with for key, val := range arr. Here, key represents the index of the element and val represents the value at that index in the array arr.


This will iterate over the array and print the index and value on each iteration. The output will be:

1
2
3
4
5
6
7
8
Key: 0
Value: 1
Key: 1
Value: 2
Key: 2
Value: 3
Key: 3
Value: 4