Last week, Go 1 .23 entered the freeze period, meaning no new features will be added, and any already added features are unlikely to be removed. This is a great opportunity to preview the upcoming changes. In this article, Let’s learn about the new iter package.
This article is first published in the medium MPP plan. If you are a medium user, please follow me in medium. Thank you very much.
In Go 1.22, the range over func experimental feature was introduced, but it needed to be enabled by the parameter GOEXPERIMENT=rangefunc
. In Go 1.23, this kind of iteration can be directly implemented with code.
|
|
yield
is a conventional name for callable functions passed into iterators.
Now, let’s consider how we would write the code to achieve the same functionality without using the iter
package:
|
|
Performance Comparison
Let’s compare the performance of the two methods:
|
|
The result is clear: ToUpperByIter
performs better because it doesn’t reallocate a new slice, making it more efficient than the previous method.
The goal of iter
The iter
package aims to provide a unified and efficient iteration method. It offers a standard iteration interface for custom container classes (especially after the introduction of generics) and can replace some existing APIs that return slices. By using iterators and leveraging compiler optimization, performance can be improved. Additionally, it provides a standard iteration mechanism suitable for functional programming styles.
The Use of iter
iter
supports two types of iterators:
|
|
The map
package has already been used iter
to add methods such as All
and Keys
. Here is a reference to its implementation:
|
|
Community Opinions
Photo by Ana Flávia on Unsplash
“In my opinion, yield is a complicated enough concept to cause a lot of bad, incomprehensible code to appear. This suggestion provides only a syntax sugar for writing something that is already more than possible in the language. I believe this goes against the rule of
_One problem - one solution_
. Please, let Go stay boring." Source
This is a common objection within the community. yield
is not easy to understand, and we can implement iterators in many ways.
Conclusion
I support the addition of iter
.
The iter
package offers numerous possibilities for developers aiming to streamline their code and adopt more functional programming practices. However, its reception is mixed due to concerns about performance, complexity, and the learning curve.
As with any new tool, the key is to balance its use where it offers clear benefits while remaining mindful of the potential drawbacks. The Go community will undoubtedly continue to explore and debate the best ways to harness iter
’s power without compromising the language’s foundational principles.