Going Backward
The Go standard library includes a slices package with a function named Backward. This function enables iterating over the elements of a slice in reverse order. However, some programmers might find the implementation more complex than necessary. To understand this complexity, imagine a pre-iterator era programmer who decides to create a function for walking a slice in reverse order.
They create a simple and reliable implementation, but it creates a copy of the slice, which can be inefficient for large slices. To avoid copying, they return a closure that knows the current position in the original slice, reducing memory allocation to O(1). The calling code, however, becomes imperative, prompting the programmer to complicate Backward's signature.
They make it return an iterator function that takes a callback as an argument, allowing the callback to signal when to stop traversal early. The signature looks heavy, so they create a separate type for the return value. Since the result's signature differs from an ordinary range over a slice, they add a new type called Seq2. The Go spec reveals that user-defined slices, with an underlying type of []int, can also be used with Backward.
However, the function signatures must match for comparison, even if the underlying types are different. The programmer adds generic syntax ~T to parameterize both the element type and the slice type. After implementing Backward, the programmer considers making the traversal logic configurable, even adding a factory that produces iterator factories based on given criteria.
The complex version of Backward in the standard library serves its purpose, but for specific projects, a simpler option might be more appropriate.
Written by urgent.news from Lobsters's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.