Loops are essential tools in programming for repeating actions or iterating over data. Go provides two primary loop structures: for and for...range.
Loops allow you to execute a block of code multiple times, either for a predetermined number of iterations or until a specific condition is met. This avoids repetitive code and makes your programs more dynamic.
for Loop: Go's WorkhorseThe for loop is the most versatile loop in Go. It has a simple structure:
for initialization; condition; post-iteration { // Code to be executed repeatedly }
Counting to 10:
for i := 0; i < 10; i++ { fmt.Println(i) }
Iterating over a slice:
numbers := []int{1, 2, 3, 4, 5} for i := 0; i < len(numbers); i++ { fmt.Println(numbers[i]) }
++ (Increment): Increases the value of a variable by 1.-- (Decrement): Decreases the value of a variable by 1.+= (Add and Assign): Adds a value to a variable and assigns the result to the variable.-= (Subtract and Assign): Subtracts a value from a variable and assigns the result to the variable.You can omit the condition in a for loop to create an infinite loop:
for { // Code that runs indefinitely }
continue Keyword: Skipping to the Next IterationThe continue keyword jumps to the beginning of the next iteration of the loop, skipping any remaining code in the current iteration:
for i := 0; i < 10; i++ { if i%2 == 0 { continue // Skip even numbers } fmt.Println(i) }
break Keyword: Exiting the LoopThe break keyword exits the loop completely, ending the loop's execution:
for i := 0; i < 10; i++ { if i == 5 { break // Exit the loop when i is 5 } fmt.Println(i) }
No notes yet. Click "New Note" to add one.