go / beginner
Snippet
For Loop as While Alternative
Go has only one loop keyword: `for`. There is no `while` keyword. The `for` loop without initialization and post statements acts as a while loop. This makes Go simpler while remaining powerful.
snippet.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package mainimport "fmt"func main() {count := 0// Go has no while keyword, for is used insteadfor count < 5 {fmt.Println("Count:", count)count++}// Classic for loopfor i := 0; i < 3; i++ {fmt.Println("i:", i)}}
Breakdown
1
for count < 5 { }
For without init/post becomes a while-like loop, runs while condition is true
2
count++
Increment operator increases count by 1 each iteration
3
for i := 0; i < 3; i++
Classic three-part for loop with initializer, condition, and increment