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 ...

Get 100 Go Mistakes and How to Avoid Them now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.