Algorithm


In Go programming language, the range keyword is used in various contexts to iterate over elements of data structures like arrays, slices, maps, strings, or channels. Its usage can vary slightly depending on the type of data structure you are working with

Code Examples

#1 Go Lang for range with Array

Code - Golang Programming

// Program using range with array

package main
import "fmt"
 
func main() {
 
  // array of numbers
  numbers := [5]int{21, 24, 27, 30, 33}
 
  // use range to iterate over the elements of array
  for index, item := range numbers {
    fmt.Printf("numbers[%d] = %d \n", index, item)
  }

}
Copy The Code & Try With Live Editor

Output

x
+
cmd
numbers[0] = 21
numbers[1] = 24
numbers[2] = 27
numbers[3] = 30
numbers[4] = 33

#2 Range with string in Golang Programming

Code - Golang Programming

// Program using range with string

package main
import "fmt"

func main() {
  string := "Golang"
  fmt.Println("Index: Character")

  // i access index of each character
  // item access each character
  for i, item := range string {
    fmt.Printf("%d= %c \n", i, item)
  }

}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Index: Character
0: G
1: o
2: l
3: a
4: n
5: g

#3 For Range with GoLang map

Code - Golang Programming

// Program using range with map

package main
import "fmt"

func main() {

  // create a map
  subjectMarks := map[string]float32{"Java": 80, "Python": 81, "Golang": 85}
  fmt.Println("Marks obtained:")

  // use for range to iterate through the key-value pair
  for subject, marks := range subjectMarks {
    fmt.Println(subject, ":", marks)
  }

}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Marks Obtained:
Java: 80
Python: 81
Golang: 85

#4 Access keys of Map using GoLang Range

Code - Golang Programming

// Program to retrieve the keys of a map

package main
import "fmt"

func main() {

  // create a map
  subjectMarks := map[string]float32{"Java": 80, "Python": 81, "Golang": 85}

  fmt.Println("Subjects:")
  for subject := range subjectMarks {
    fmt.Println( subject)
  }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Subjects:
Java
Python
Golang
Advertisements

Demonstration


Range in Go Lang Programming