November 2nd, 2024

Ranging over Functions in Go 1.23

Go 1.23 introduces ranging over functions, allowing iteration over custom data structures with for-range loops, simplifying iterator creation, supporting early termination, and enhancing code clarity through various examples.

Read original articleLink Icon
Ranging over Functions in Go 1.23

Go 1.23 introduces a significant feature: ranging over functions, enhancing the language's iteration capabilities. This feature allows developers to use the familiar for-range loop not only with built-in types like slices and maps but also with custom data structures. The article discusses how this new functionality simplifies iteration over generic containers, which previously required custom iteration methods. A key example is the implementation of an associative list (AssocList) that can now be iterated over using a standard for-range loop. The new method, All, returns a function that accepts a yield function, enabling the iteration process. The article also explains the mechanics behind this feature, detailing how the compiler transforms the for-range loop into calls to the yield function, allowing for early termination of iteration when necessary. Additionally, it covers more complex iteration patterns, such as recursive iterators for binary trees and examples of using the new feature with existing types like bufio.Scanner. Overall, this enhancement streamlines the process of creating and using iterators in Go, promoting a more idiomatic approach to iteration.

- Go 1.23 introduces ranging over functions, allowing iteration over custom data structures.

- The new feature simplifies the creation of iterators for generic containers.

- The for-range loop can now be used with functions that yield values, enhancing code clarity.

- Early termination of iteration is supported, improving control over the iteration process.

- The article provides examples, including associative lists and binary trees, demonstrating the new functionality.

Link Icon 1 comments
By @killingtime74 - 6 months
I recently worked on a Go code base. noticed that it felt like 40% of my code was boilerplate compared to kotlin/rust/python. Hopefully features like this will bring that percentage down