Go For Loops

Go Tutorial

Go (Golang) for Loops

In Go For Loops is the only looping statement.
It is flexible enough to act like a while loop, for-each loop, and infinite loop.


 Basic for Loop (Traditional)

Syntax

Example


for as a While Loop

Go does not have while. Use for instead.


 Infinite Loop

Used in servers and background processes.


for with break and continue

break

continue


for with range (Most Common)

Used to loop over arrays, slices, strings, maps.

Slice Example


 

Ignore index:


 Looping Over Strings (Unicode Safe)


 


 Looping Over Maps


 

⚠ Map order is not guaranteed.


 Nested Loops


 Loop Control with Labels


 Common Mistakes

  •  Forgetting loop condition → infinite loop
  •  Modifying slice while ranging incorrectly
  •  Assuming map order

Summary

  • Go uses only for

  • Can act as for, while, infinite loop

  • range simplifies iteration

  • Supports break, continue, labels

You may also like...