foreach Support by Range Member Functions

Learn about the foreach support by range member functions.

foreach

As you remember from the foreach loop chapter, both how foreach works and the types and numbers of loop variables that it supports depend on the kind of collection:

  • For slices, foreach provides access to elements with or without a counter.

  • For associative arrays, to values with or without keys; for number ranges, to the individual values.

  • For library types, foreach behaves in a way that is specific to that type, e.g., for File, it provides the lines of a file.

It is also possible to define the behavior of foreach for user-defined types. There are two methods of providing this support:

  • Defining range member functions, which allows using the user-defined type with other range algorithms as well

  • Defining one or more opApply member functions

Of the two methods, opApply has priority: If it is defined, the compiler uses opApply otherwise, it considers the range member functions. However, in most cases range member functions are sufficient, easier, and more useful.

foreach needs not be supported for every type. Iterating over an object makes sense only if that object defines the concept of a collection.

Get hands-on with 1000+ tech skills courses.