Learn Golang
  • Learn Go
  • The Basics
    • Installing Go
    • Hello World
  • Language Features
    • Basic Input Output
    • Variable Basics
    • Control Statements
    • Loops
    • Functions
    • Recursion
  • Data Structures
    • Arrays
    • Slices
    • Maps
    • Pointers
    • Structs
  • Other Concepts
    • Sorting
    • Interfaces
    • Generics
    • Goroutines
  • References
Powered by GitBook
On this page
  1. Language Features

Loops

Looping in golang is easy! There is only one type of loop

PreviousControl StatementsNextFunctions

Last updated 2 years ago

CtrlK

The for loop is the only looping construct in golang. Although golang does not have reserved words like while for loops where the condition is evaluated in the loop body, the for loop can be extended to support such patterns. Let's look at some examples below

1. The classic three-statement for loop

Golang's for statement support the classic three-statement for loops, where we have an initial value, a condition that is tested every iteration of the loop, and some action to perform on the loop variant. Here's how that works in golang

// for loop with initializer, condition, and increment
fmt.Println("For loop")
for j := 0; j < 5; j++ {
  fmt.Println("The current value is ", j)
}

2. While loops

We can write a while loop using the for keyword. The thing worth noting here is the loop variable initialization happens outside the loop.

// while loops in go use the for <condition> format
fmt.Println("While loop")
i := 0
for i < 5 {
  fmt.Println(i)
  i++
}

3. Infinite Loops

Do not run the following code below. It is an infinite loop for demonstration only

For loops without an exit condition will result in an infinite loop

// infinite loop example.
// caution: do not run the following code
fmt.Println("Infinite loop")
k := 0
for {
  fmt.Println(k)
  k++
}

4. For Each Loops

foreach loops are a useful construct in many languages and golang provides support for this through the range keyword. Range loops are useful when we need to iterate over individual elements of a list, array, or map (or other container types)

// for-each loops (also known as range loops)
fmt.Println("\nRange loop")
nums := []int{1, 2, 3, 4, 5}
for index, num := range nums {
  fmt.Println(index, num)
}

5. Break/Continue Statement in loops

We can skip over parts of the loop with the continue keyword, or break out of loops using break in the loop body.

// break loop
fmt.Println("Break loop")
for l := 0; l < 5; l++ {
  if l == 3 {
    // exit the loop when l == 3
    break
  }
  fmt.Println(l)
}

// continue loop
fmt.Println("Continue loop")
for m := 0; m < 5; m++ {
  if m == 3 {
    // skips over printing 3
    continue
  }
  fmt.Println(m)
}