Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between for loop construct vs range keyword in go

Tags:

go

Consider the following code which just prints all the ENV vars

package main

import (
    "fmt"
    "os"
)

func main() {
    for i, env := range os.Environ() {
        fmt.Println(i, env)
    }
}

Here, os.Environ() is supposed to return array of strings([] string), to loop over it. I need to to use range keyword & also for loop. Question is:

  1. Why are both for & range required? is it possible to use for loop for this as []string is already an array & we can iterate over arrays right?
  2. In the above code what does range do? and what does for loop does?

Sorry if this question is too stupid, I am just starting with Go

like image 981
CuriousMind Avatar asked Jun 20 '15 15:06

CuriousMind


1 Answers

As mentioned in Range Clauses:

A range clause provides a way to iterate over a array, slice, string, map, or channel.

If you want to iterate over an []string, you need range.

A For statement doesn't always use range.

ForStmt = "for" [ Condition | ForClause | RangeClause ] Block .

You have:

  • In its simplest form, a "for" statement specifies the repeated execution of a block as long as a boolean condition evaluates to true

  • A "for" statement with a ForClause is also controlled by its condition, but additionally it may specify an init and a post statement, such as an assignment, an increment or decrement statement

  • A "for" statement with a "range" clause iterates through all entries of an array, slice, string or map, or values received on a channel. For each entry it assigns iteration values to corresponding iteration variables if present and then executes the block.

like image 87
VonC Avatar answered Sep 30 '22 15:09

VonC