What is "range" actually? Is it a function?


One of the preferred way to loop through arrays and slices is to use range like this

arr = []int{1, 2}

for index, item := range arr {

I know how range works, I’ve been using it multiple times. But I’m still not sure what it is behind the scene. Is it a function and a modification of range(arr)? The fact that it returns 2 variables make me think that way, but I need a confirmation.

What’s the implementation behind it?


Range is one of the keywords according to the spec.

The following keywords are reserved and may not be used as identifiers.

break        default      func         interface    select
case         defer        go           map          struct
chan         else         goto         package      switch
const        fallthrough  if           range        type
continue     for          import       return       var

For statements with range clause

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.

RangeClause = [ ExpressionList "=" | IdentifierList ":=" ] "range" Expression .

Answered By – The Fool

Answer Checked By – Jay B. (GoLangFix Admin)

Leave a Reply

Your email address will not be published.