Loops in Go - Golang (Making Go Repeat Itself Without Complaints!)

Go (or Golang, for the sophisticated folks) doesn’t like doing the same thing over and over manually—just like you wouldn’t want to copy-paste the same line of code 100 times. That’s where loops come in! With for and range, you can make Go repeat actions efficiently without losing your sanity. 

1. The for Loop (Go’s Favorite Workout Routine)

The for loop is the only looping construct in Go (no while, no do-while, just for). But don’t worry—it’s flexible enough to handle everything!

Basic for Loop

package main
import "fmt"

func main() {
    for i := 1; i <= 5; i++ {
        fmt.Println("Iteration:", i)
    }
}

Output:

Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5

The loop starts at i = 1, runs until i <= 5, and increases i after every iteration. Classic!

2. The Infinite for Loop (For When You Want Go to Work Forever)

An infinite loop runs forever (or until you stop it). Just remove the condition!

package main
import "fmt"

func main() {
    for {
        fmt.Println("This will go on forever... unless you press Ctrl+C!")
    }
}

Warning: Run this at your own risk!

3. The for Loop as a while Loop (Because Go is Special)

Since Go doesn’t have a while loop, you can mimic it using for.

package main
import "fmt"

func main() {
    i := 1
    for i <= 5 {
        fmt.Println("Counting:", i)
        i++
    }
}

Output:

Counting: 1
Counting: 2
Counting: 3
Counting: 4
Counting: 5

This behaves exactly like a while loop in other languages!

4. The range Loop (Looping Through Collections Like a Pro)

range is used to iterate over arrays, slices, maps, and strings effortlessly.

Looping Over an Array

package main
import "fmt"

func main() {
    numbers := []int{10, 20, 30, 40, 50}
    for index, value := range numbers {
        fmt.Printf("Index: %d, Value: %d\n", index, value)
    }
}

Output:

Index: 0, Value: 10
Index: 1, Value: 20
Index: 2, Value: 30
Index: 3, Value: 40
Index: 4, Value: 50

range simplifies looping through lists. You get both the index and the value effortlessly!

Looping Over a String (Characters in Disguise)

package main
import "fmt"

func main() {
    text := "GoLang"
    for index, char := range text {
        fmt.Printf("Index: %d, Character: %c\n", index, char)
    }
}

Output:

Index: 0, Character: G
Index: 1, Character: o
Index: 2, Character: L
Index: 3, Character: a
Index: 4, Character: n
Index: 5, Character: g

Go treats characters as runes (Unicode points), so you can loop through text effortlessly.

Loops help you automate repetitive tasks, making your Go programs smarter and more efficient. Now, go forth and loop responsibly—don’t accidentally create an infinite loop unless you want Go to take over your CPU forever! 

Post a Comment

0 Comments