Skip to content

Commit

Permalink
Merge pull request #1971 from xushiwei/q
Browse files Browse the repository at this point in the history
spec: for stmt
  • Loading branch information
xushiwei authored Aug 25, 2024
2 parents 1cb7838 + dbf5d67 commit 17ff401
Showing 1 changed file with 77 additions and 0 deletions.
77 changes: 77 additions & 0 deletions doc/spec-mini.md
Original file line number Diff line number Diff line change
Expand Up @@ -990,3 +990,80 @@ if x := f(); x < y {
return y
}
```

### For statements

A "for" statement specifies repeated execution of a block. There are three forms: The iteration may be controlled by a single condition, a "for" clause, or a "range" clause.

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

#### For statements with single condition

In its simplest form, a "for" statement specifies the repeated execution of a block as long as a boolean condition evaluates to true. The condition is evaluated before each iteration. If the condition is absent, it is equivalent to the boolean value true.

```go
for a < b {
a *= 2
}
```

#### For statements with for clause

A "for" statement with a ForClause is also controlled by its condition, but additionally it may specify an init and a post statement, such as an assignment, an increment or decrement statement. The init statement may be a [short variable declaration](#short-variable-declarations), but the post statement must not.

```go
ForClause = [ InitStmt ] ";" [ Condition ] ";" [ PostStmt ] .
InitStmt = SimpleStmt .
PostStmt = SimpleStmt .
```

For example:

```go
for i := 0; i < 10; i++ {
f(i)
}
```

If non-empty, the init statement is executed once before evaluating the condition for the first iteration; the post statement is executed after each execution of the block (and only if the block was executed). Any element of the ForClause may be empty but the [semicolons]() are required unless there is only a condition. If the condition is absent, it is equivalent to the boolean value true.

```go
for cond { S() } is the same as for ; cond ; { S() }
for { S() } is the same as for true { S() }
```

Each iteration has its own separate declared variable (or variables) [Go 1.22](). The variable used by the first iteration is declared by the init statement. The variable used by each subsequent iteration is declared implicitly before executing the post statement and initialized to the value of the previous iteration's variable at that moment.

```go
var prints []func()
for i := 0; i < 5; i++ {
prints = append(prints, func() { println(i) })
i++
}
for _, p := range prints {
p()
}
```

prints

```
1
3
5
```

Prior to [Go 1.22], iterations share one set of variables instead of having their own separate variables. In that case, the example above prints

```
6
6
6
```

#### For statements with range clause

TODO

0 comments on commit 17ff401

Please sign in to comment.