You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The `for` loop is one of the most commonly used statements to repeatedly execute some logic.
6
-
The basic `for` loop has three components separated by semicolons:
7
-
8
-
- the **init statement**: executed once before the first iteration
9
-
- the **condition expression**: evaluated before every iteration
10
-
- the **post statement**: executed at the end of every iteration
5
+
The for loop is one of the most commonly used statements to repeatedly execute some logic. In Go it consists of the `for` keyword, a header and a code block that contains the body of the loop wrapped in curly brackets. The header consists of 3 components separated by semicolons `;`: init, condition and post.
11
6
12
7
```go
13
-
forinitialization; condition; step {
14
-
// code that is executed repeatedly as long as the condition is true
8
+
forinit; condition; post {
9
+
//loop body - code that is executed repeatedly as long as the condition is true
15
10
}
16
11
```
17
12
18
-
**Note:** Unlike other languages like C, Java, or JavaScript there are no parentheses surrounding the three components of the `for` statement and the braces `{ }` are always required.
13
+
- The **init** component is some code that runs only once before the loop starts.
14
+
- The **condition** component must be some expression that evaluates to a boolean and controls when the loop should stop. The code inside the loop will run as long as this condition evaluates to true. As soon as this expression evaluates to false, no more iterations of the loop will run.
15
+
- The **post** component is some code that will run at the end of each iteration.
19
16
20
-
## Header
17
+
**Note:** Unlike other languages, there are no parentheses `()` surrounding the three components of the header. In fact, inserting such parenthesis is a compilation error. However, the braces `{ }` surrounding the loop body are always required.
21
18
22
-
The initialization usually sets up a counter variable, the condition checks whether the loop should be continued or stopped and the step increments the counter at the end of each repetition.
19
+
## For Loops - An example
23
20
24
-
The individual parts of the header are separated by semicolons.
21
+
The init component usually sets up a counter variable, the condition checks whether the loop should be continued or stopped and the post component usually increments the counter at the end of each repetition.
25
22
26
23
```go
27
-
28
-
fori:=1; i <= 10; i++ {
24
+
fori:=1; i < 10; i++ {
29
25
fmt.Println(i)
30
26
}
31
27
```
32
28
33
-
Defining the step is often done using the increment or decrement statement as shown in the example above.
29
+
This loop will print the numbers from `1` to `9` inclusivé.
30
+
Defining the step is often done using an increment or decrement statement, as shown in the example above.
34
31
35
-
Also, the init and post statements are optional.
36
32
37
-
```go
38
-
i:=1
33
+
## Optional components of the header
39
34
40
-
for i <= 3 {
41
-
42
-
fmt.Println(i)
43
-
i = i + 1
44
-
45
-
}
46
-
```
47
-
48
-
## The "while" loop
49
-
50
-
At that point you can drop the semicolons: C's `while` is spelled `for` in Go.
35
+
The init and post components of the header are optional:
51
36
52
37
```go
53
-
varsumint= 1
38
+
varsum = 1
54
39
for sum < 1000 {
55
40
sum += sum
56
41
}
57
42
fmt.Println(sum)
58
43
// Output: 1024
59
44
```
60
45
61
-
## Break, Continue and Labels
46
+
This is similar to a `while` loop in other languages.
47
+
48
+
In Go, there is no `while` keyword. A `while` loop can be expressed in Go by writing a `for` loop without the init and post parts of the header, like in the example above.
49
+
50
+
62
51
63
-
Inside a loop body you can use the `break` keyword to stop the execution of the loop entirely.
52
+
## Break and Continue
53
+
54
+
Inside a loop body you can use the `break` keyword to stop the execution of the loop entirely:
64
55
65
56
```go
66
57
forn:=0; n <= 5; n++ {
@@ -75,7 +66,7 @@ for n := 0; n <= 5; n++ {
75
66
// 2
76
67
```
77
68
78
-
In contrast, the keyword `continue` only stops the execution of the current iteration and continues with the next one.
69
+
In contrast, the keyword `continue` only stops the execution of the current iteration and continues with the next one:
79
70
80
71
```go
81
72
forn:=0; n <= 5; n++ {
@@ -92,10 +83,36 @@ for n := 0; n <= 5; n++ {
92
83
93
84
## Infinite for loop
94
85
95
-
If you forget or omit the loop condition it loops forever.
86
+
The condition part of the loop header is also optional. In fact, you can write a loop with no header:
96
87
97
88
```go
98
89
for {
99
90
// Endless loop...
100
91
}
101
92
```
93
+
94
+
This loop will never end and will only ever finish if the program exits or has a `break` in its body.
95
+
96
+
## Labels and goto
97
+
98
+
When we use `break`, Go will stop running the most inner loop. Similarly, when we use `continue`, Go will run the next iteration of the most inner loop.
99
+
100
+
However, this is not always desirable. We can use labels together with `break` and `continue` to specifcy exactly from which loop we want to exit or continue, respectively.
101
+
102
+
In this example we are creating a label `OuterLoop`, that will refer to the most outter loop. In the most inner loop, to say that we want exit from the most outter loop, we then use `break` followed by the name of the label of the most outter loop:
103
+
104
+
```go
105
+
OuterLoop:
106
+
fori:=0; i < 10; i++ {
107
+
forj:=0; j < 10; j++ {
108
+
// ...
109
+
break OuterLoop
110
+
}
111
+
}
112
+
```
113
+
114
+
Using labels with `continue` would also work, in which case, Go would continue in the next iteration of the loop referenced by the label.
115
+
116
+
Go also has a `goto` keyword that works in a similar way and allows us to jump to from a piece of code to another labeled piece of code.
117
+
118
+
**Warning:** Even though Go allows to jump to a piece of code marked with a label with `continue`, `break` or `goto`, using this feature of the language can easily make the code very hard to read. For this reason, using labels is often not recommended.
Copy file name to clipboardExpand all lines: concepts/for-loops/introduction.md
+9-8Lines changed: 9 additions & 8 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,20 +1,21 @@
1
+
# Introduction
1
2
## General syntax
2
3
3
-
The for loop is one of the most commonly used statements to repeatedly execute some logic. The basic `for` loop has three components separated by semicolons:
4
-
5
-
- the **init statement**: executed before the first iteration
6
-
- the **condition expression**: evaluated before every iteration
7
-
- the **post statement**: executed at the end of every iteration
4
+
The for loop is one of the most commonly used statements to repeatedly execute some logic. In Go it consists of the `for` keyword, a header and a code block that contains the body of the loop wrapped in curly brackets. The header consists of 3 components separated by semicolons `;`: initilization, condition and step.
8
5
9
6
```go
10
7
for initialization; condition; step {
11
-
// code that is executed repeatedly as long as the condition is true
8
+
//loop body - code that is executed repeatedly as long as the condition is true
12
9
}
13
10
```
14
11
15
-
**Note:** Unlike other languages like C, Java, or JavaScript there are no parentheses surrounding the three components of the `for` statement and the braces `{ }` are always required.
12
+
- The **initialization** component is some code that runs only once before the loop starts.
13
+
- The **condition** component must be some expression that evaluates to a boolean and controls when the loop should stop. The code inside the loop will run as long as this condition evaluates to true. As soon as this expression evaluates to false, no more iterations of the loop will run.
14
+
- The **step** component is some code that will run at the end of each iteration.
15
+
16
+
**Note:** Unlike other languages, there are no parentheses `()` surrounding the three components of the header. In fact, inserting such parenthesis is a compilation error. However, the braces `{ }` surrounding the loop body are always required.
16
17
17
-
## Header
18
+
## For Loops - An example
18
19
19
20
The initialization usually sets up a counter variable, the condition checks whether the loop should be continued or stopped and the step increments the counter at the end of each repetition.
0 commit comments