iterate is Julia’s generic function for implementing the iteration protocol. A collection returns its next element together with a state value, or returns nothing when iteration is complete. Once a type supports this interface, for loops and functions such as map, reduce, and filter can operate on it. section 12.3 section 12.8
Implement the minimum protocol with two methods:
- iterate(iter) returns the first element and the initial state. section 12.3
- iterate(iter, state) returns the current element and next state, or nothing at the end. section 12.3 section 12.4.1
- Import iterate from Base before extending it, because for loops call Base.iterate. section 12.4.1
- Use any useful state representation; it may be an index, an object, or another value that records the current position. section 12.5
Iterating over a mixed engine cluster
A cluster initially fails in a for loop with MethodError because it has no iterate methods. Define iterate(cluster) to return the first engine and state 2, then define iterate(cluster, i) to return cluster.engines[i] and i + 1 until i exceeds the engine count. Julia’s for loop effectively repeats these calls until nothing is returned. Afterward, mass(cluster) and thrust(cluster) can reuse sum over the cluster. section 12.4.1
Use the protocol table to distinguish the start call from subsequent state-driven calls. section 12.3
Rocket stages demonstrate state that is not an index: each state can be the next Rocket object. A staged rocket advances through nextstage, while an ordinary Rocket returns nothing. A for loop works with these methods, but map and collect also require length, so iteration alone does not provide every collection capability. section 12.5

