Home > Blockchain >  What is "range" actually? Is it a function?
What is "range" actually? Is it a function?

Time:02-11

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 {
  continue
}

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?

CodePudding user response:

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 .

CodePudding user response:

A for with a range clause iterates over arrays, slices, map, strings and values received on a channel. The range keyword is syntax used by the compiler to distinguish this type of iteration from other iteration in a for statement.

The compiler implements for with a range clause. The specification describes for with a range clause in detail.

  •  Tags:  
  • go
  • Related