Understanding For Loops in Golang

In Golang a for loop is a way to loop through an iterable.

The most basic For Loop

i := 0 for i <= 3 { i = i + 1 }
Code language: Go (go)

A classic For Loop

for i := 7; i <= 9; i++ { // do something }
Code language: Go (go)

For Loop without Conditions

A for without a condition will loop forever, until either a break or return is hit.

for { // do something break // kill the loop }
Code language: Go (go)

When to use continue

A continue will move to the next iteration of the loop

for i := 0; i <= 5; i++ { if i%2 == 0 { // skip if even number continue // move to next iteration } // do something with odd number }
Code language: Go (go)

Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments