Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang

What is the for-range loop in Golang?

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

A for loop is used to iterate over elements in a variety of data structures (e.g., a slice, an array, a map, or a string).

The for statement supports one additional form that uses the keyword range to iterate over an expression that evaluates to an array, slice, map, string, or channel.

svg viewer

Syntax

The basic syntax for a for-range loop is:

for index, value := range mydatastructure {
		fmt.Println(value)
	}
  • index is the index of the value we are accessing.
  • value is the actual value we have on each iteration.
  • mydatastructure holds the data structure whose values will be accessed in the loop.

Note that the above example is highly generalized. The case-by-case examples given below will help you understand the syntax further.​

Code

1. Iterating over a string

The for-range loop can be used to access individual characters in a string.

package main
import "fmt"

func main() {
  for i, ch := range "World" {
    fmt.Printf("%#U starts at byte position %d\n", ch, i)
  }
}

2. Iterating over a map

The for-range loop can be used to access individual key-value pairs in a map.

package main
import "fmt"

func main() {
  m := map[string]int{
    "one":   1,
    "two":   2,
    "three": 3,
  }
  for key, value := range m {
      fmt.Println(key, value)
  }
}

3. Iterating over channels

For channels, the iteration values are the successive values sent on the channel until its close.

package main
import "fmt"

func main() {
  mychannel := make(chan int)
  go func() {
      mychannel <- 1
      mychannel <- 2
      mychannel <- 3
      close(mychannel)
  }()
  for n := range mychannel {
      fmt.Println(n)
  }
}

RELATED TAGS

golang
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring