4 Control structures

 

This chapter covers

  • How a range loop assigns the element values and evaluates the provided expression
  • Dealing with range loops and pointers
  • Preventing common map iteration and loop- breaking mistakes
  • Using defer inside a loop

Control structures in Go are similar to those in C or Java but differ from them in significant ways. For example, there is no do or while loop in Go, only a generalized for. This chapter delves into the most common mistakes related to control structures, with a strong focus on the range loop, which is a common source of misunderstanding.

4.1 #30: Ignoring the fact that elements are copied in range loops

A range loop is a convenient way to iterate over various data structures. We don’t have to handle an index and the termination state. Go developers may forget or be unaware of how a range loop assigns values, leading to common mistakes. First, let’s remind ourselves how to use a range loop; then we’ll look at how values are assigned.

4.1.1 Concepts

A range loop allows iterating over different data structures:

  • String
  • Array
  • Pointer to an array
  • Slice
  • Map
  • Receiving channel

4.1.2 Value copy

4.2 #31: Ignoring how arguments are evaluated in range loops

4.2.1 Channels

4.2.2 Array

4.3 #32: Ignoring the impact of using pointer elements in range loops