为什么在 Golang 中没有 for range 的帖子?

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

Why there is no post in for range ? Golang

问题

我想在每个范围循环之后递增一个变量。然而,使用标准的 for init; condition; post { } 语法似乎不可能实现这一点,所以我想知道为什么。以下是我尝试的代码:

for item := range itemsList; page++ {

}

似乎唯一的方法是这样做:

for item := range itemsList{

   page++
}

这种写法看起来没有第一种写法那么好看。

英文:

I would like to increment a variable after each range loop. However it seems it's not possible using the standard ( for init; condition; post { } ) for syntax therefore I'm wondering why . Here is what I'm trying to do

	for item := range itemsList; page++ {

}

It seems the only way to do this is

    	for item := range itemsList{
    
       page++
    }

which doesn't look as nice as the first one.

答案1

得分: 8

for语句规范确实提到了Range子句可以独立存在。

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

后置语句则是ForClause的一部分:

ForClause = [ InitStmt ] ";" [ Condition ] ";" [ PostStmt ] .

这意味着后置语句只在初始化和条件的上下文中有效,以便在每次执行块后可能改变条件(仅在块被执行后才执行)。

在Range子句中没有这种需要(使条件停止循环),因为循环已经遍历了范围的所有元素(数组、切片、字符串、映射或允许接收操作的通道),这足以使循环停止。

在开始循环之前(或者至少在开始循环之前),会对范围表达式进行一次求值(至少求得其长度)。在每次执行块后不需要做任何更改。

因此,尝试向范围循环中添加后置语句将生成编译错误,如下所示:

expected '{', found ';'
英文:

The for statement specification does mention that a Range Clause stands alone.

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

As opposed to a Post Statement, which is part of:

ForClause = [ InitStmt ] ";" [ Condition ] ";" [ PostStmt ] .

That means a post statement is only valid in the context of an initialization and a condition, in order to potentially make that condition change (since it is executed after each execution of the block, and only if the block was executed).

There is no such need (making a condition stops a loop) in a Range clause, where the fact that the loop has been done over all the elements of a range (of an array, slice, string, map, or channel permitting receive operations) is enough for the loop to stops.

A range expression is evaluated once before beginning the loop (or at least its length is). There is no need to change anything after each execution of the block.

So trying to add a post statement to a range loop would generate a compilation error like:

expected '{', found ';' 

huangapple
  • 本文由 发表于 2014年5月24日 20:58:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/23845320.html
匿名

发表评论

匿名网友

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

确定