英文:
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
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 ';'
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论