for, while loops:
for, while loops
suggest changeGo has only one looping construct: for loop.
Here are basic forms.
Full form
for i := 0; i < 5; i += 2 {
fmt.Printf("i: %d\n", i)
}
i: 0
i: 2
i: 4
Every part of loop statement is optional.
Without initialization statement
i := 0
for ; i < 5; i += 2 {
fmt.Printf("i: %d\n", i)
}
i: 0
i: 2
i: 4
Without test expression
Using break to terminate the loop
i := 0
for ; ; i += 2 {
fmt.Printf("i: %d\n", i)
if i >= 5 {
break
}
}
i: 0
i: 2
i: 4
i: 6
Without increment statement
for i := 0; i < 5; {
fmt.Printf("i: %d\n", i)
i += 2
}
i: 0
i: 2
i: 4
Infinite loop
i := 0
for {
fmt.Printf("i: %d\n", i)
i += 2
if i >= 5 {
break
}
}
i: 0
i: 2
i: 4
for loop over a slice with range
a := []int{1, 3, 5}
for idx, value := range a {
fmt.Printf("idx: %d, value: %d\n", idx, value)
}
idx: 0, value: 1
idx: 1, value: 3
idx: 2, value: 5
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents
4
Strings
5
Pointers
6
Arrays
7
Slices
8
Maps
9
Structs
10
Interfaces
13
for, while loops
15
Functions
16
Methods
18
Defer
20
Concurrency
22
Mutex
23
Packages
27
Logging
30
JSON
31
XML
32
CSV
33
YAML
34
SQL
35
HTTP Client
36
HTTP Server
38
Reflection
39
Context
40
Package fmt
41
OS Signals
42
Testing
49
gob
50
Plugin
53
Console I/O
54
Cryptography
59
Contributors