All the Ways to Write for Loops in Go
Tags: go
Published: 2021-04-16 05:35:30

---
title: All the Ways to Write for Loops in Go
published: true
date: 2021-04-10 14:42:55 UTC
tags: Golang
canonical_url: https://qvault.io/golang/golang-for-loop/
---

 ![loop architecture](https://qvault.io/wp-content/uploads/2021/04/loop-architecture.jpeg "loop architecture")

The post [All the Ways to Write for Loops in Go](https://qvault.io/golang/golang-for-loop/) first appeared on [Qvault](https://qvault.io).

A for loop executes a block of code repeatedly, and in Golang, there are several different ways to write one.

1. [The standard three-component loop](#standard)
2. [For-range loop](#range)
  1. [Range over slice](#range-slice)
  2. [Range over map](#range-map)
  3. [Range over channel](#range-channel)
  4. [Range over string](#range-string)
3. [While loop](#while)
4. [Optional components loop](#optional-components)
5. [Infinite loop](#infinite)
6. [Break from a loop](#break)
7. [Continue (skip to the next iteration) in a loop](#continue)

## #1 The standard three-component loop

Go has fairly standard syntax for the three-component loop you’re probably used to from C, Java, or JavaScript. The big difference is the lack of parentheses surrounding the components.

```
for i := 0; i < 100; i++ {
    sum += i
}
```

The three components are the init statement, `i := 0`, the condition, `i < 100`, and the post statement, `i++`. The steps of executing the loop are as follows.

1. The init statement executes and variables declared there are made available to the scope of the loop’s body.
2. The condition is computed. If it evaluates to `true` then the body runs, otherwise the loop is complete.
3. The post statement runs.
4. Step 2 is repeated.

## #2 For-range loop

More often than not it seems, it’s useful to loop over a collection of items like a map, slice, channel, or string. While you can use a traditional three-component loop, Go makes it easy by using the `range` keyword.

### Range over a slice in Go

```
fruits := []string{"apple", "banana", "pear"}
for i, fruit := range fruits {
    fmt.Println(i, s)
}
// prints:
// 0 apple
// 1 banana
// 2 pear
```

### Range over a map in Go

```
ages := map[string]int{
    "lane": 26,
    "preston": 28,
    "rory": 21,
}
for name, age := range ages {
    fmt.Println(name, age)
}
// prints:
// lane 26
// preston 28
// rory 21
```

### Range over a channel in Go

```
ch := make(chan int)
go func() {
    for i := 0; i < 3; i++ {
        ch <- i
    }
    close(ch)
}()

// loop ends when channel is close
for value := range ch {
    fmt.Println(value)
}
fmt.Println("channel closed")

// prints:
// 0
// 1
// 2
// channel closed
```

### Range over a string in Go

```
name := "lane"
for i, char := range name {
     // cast the rune to a string for printing 
     fmt.Println(i, string(char))
}

// prints
// 0 l
// 1 a
// 2 n
// 3 e
```

## #3 While loop

By using a single component in the for-loop signature rather than three, we can effectively build a while-loop in Golang. There is no `while` keyword in Go.

```
sum := 1
for sum < 10 {
    sum += sum
}
fmt.Println(sum)
```

## #4 Optional components loop

Building on the idea of a flexible for-loop, we can omit the init or post statements of the three-component loop as we please.

```
i := 0
for ; sum < 1000; i++ {
    sum += i
}

for i := 0; sum < 1000; {
    sum += i
    i++
}
```

This can be a useful pattern when you want something like a [do-while, or an immediate first tick from a ticker.](https://qvault.io/golang/range-over-ticker-in-go-with-immediate-first-tick/)

## #5 Infinite loop

Infinite loops are useful within goroutines when you have a worker or process that should continue perpetually.

```
sum := 0
for {
    sum++ // repeated forever
}
// never reached, loops continues on forever
```

## #6 Break from a loop

Breaking early from a loop can be useful, especially in a forever loop. The `break` keywords exits the loop immediately.

```
sum := 0
for {
    sum++
    if sum >= 1000 {
        break
    }
}
fmt.Println(sum)

// prints:
// 1000
```

## #7 Continue (skip to the next iteration) in a loop

It can be useful to skip to the next iteration of a loop early. This can be a good pattern for [guard clauses](https://qvault.io/clean-code/guard-clauses-how-to-clean-up-conditionals/) within a loop.

```
for i := 0; i < 10; i++{
    if i % 2 == 0 {
        continue
    }
    fmt.Println(i, "is odd")
}

// prints
// 1 is odd
// 3 is odd
// 5 is odd
// 7 is odd
// 9 is odd
```

## Thanks for reading, now take a course!

Interested in a high-paying job in tech? Land interviews and pass them with flying colors after taking my hands-on coding courses.

[Start coding now](https://qvault.io)

### Questions?

Follow and hit me up on Twitter [@q\_vault](https://twitter.com/q_vault) if you have any questions or comments. If I’ve made a mistake in the article be sure to [let me know](https://qvault.io/contact/) so I can get it corrected!

[Subscribe](https://mailchi.mp/5c7f5c281bbe/qvault-newsletter-subscribe) to my newsletter for more coding articles delivered straight to your inbox.