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

huangapple go评论92阅读模式
英文:

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

问题

range 是 Go 语言中用于遍历数组和切片的首选方法之一。它并不是一个函数,而是一种语法结构。range 会返回两个值,一个是当前元素的索引,另一个是当前元素的值。你可以使用这两个值在循环中进行操作。

range 的实现原理是根据被遍历的对象的类型来确定。对于数组和切片,range 会返回每个元素的索引和值。对于字符串,range 会返回每个字符的索引和 Unicode 编码。对于映射(map),range 会返回每个键值对的键和值。

在循环中,你可以选择忽略其中一个返回值,比如只需要值而不需要索引,可以使用下划线 _ 来忽略索引的变量。

希望这个解释对你有帮助!如果你还有其他问题,请随时提问。

英文:

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?

答案1

得分: 6

范围是根据规范中的关键字之一。以下是关键字列表:

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语句

带有范围子句的"for"语句遍历数组、切片、字符串、映射或从通道接收的值的所有条目。对于每个条目,如果存在相应的迭代变量,则将迭代值分配给相应的迭代变量,然后执行代码块。

范围子句的语法如下:

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

英文:

Range is one of the keywords according to the spec.

>plaintext
>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 .
>

答案2

得分: 3

一个带有range子句的for循环可以迭代数组、切片、映射、字符串和从通道接收到的值。range关键字是编译器用来区分这种类型的迭代与for语句中的其他迭代的语法。

编译器使用range子句实现for循环。规范详细描述了带有range子句的for循环

英文:

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.

答案3

得分: 0

这是一个迭代器模式,for循环使用它来获取下一个对象。

英文:

It's an iterator-pattern which the for-loop uses to get the next object from.

huangapple
  • 本文由 发表于 2022年2月11日 00:11:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/71068460.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定