Go for Loop
In Go, the for loop is the only looping construct available. It is highly versatile and can be used to implement traditional loops, condition-based loops, and even infinite loops.
Loops are essential when you need to execute a block of code repeatedly. Each repetition is called an iteration.
Basic Syntax of the for Loop
Components Explained
- Initialization: Sets up the loop variable (executed once at the start).
- Condition: Evaluated before each iteration. If true, the loop continues; if false, it stops.
- Post statement: Updates the loop variable after each iteration.
Note: These components are optional, but the loop must still be logically controlled.
Example 1: Printing Numbers
Example 2: Loop with Custom Step
This loop increments by 5 in each iteration.
Using continue in a Loop
The continue statement skips the current iteration and moves to the next one.
Using break in a Loop
The break statement immediately terminates the loop.
Nested Loops in Go
A loop can exist inside another loop. The inner loop runs completely for each iteration of the outer loop.
The range Keyword in Go
The range keyword simplifies iteration over arrays, slices, and maps. It returns both the index and the value.
Syntax
Example: Iterating with range
Ignoring Index or Value
You can use _ (blank identifier) to ignore unwanted values.
Ignore Index:
Ignore Value:
