Go 范围迭代器揭秘

  • Introduction: Using Go to write [Dolt], the world's first version-controlled SQL database. In Go 1.23, you can use the range keyword to iterate over custom collection types. Need to install Go 1.23 RC or set GOEXPERIMENT=rangefunc in Go 1.22.
  • What are range iterators: Explanation from experiment documentation was confusing. Release notes summarize the feature better. Range iterators are function types used with range keyword starting in Go 1.23. There are three types: func(func() bool), func(func(K) bool), func(func(K, V) bool), corresponding to different range loop forms. Simple examples shown.
  • Types of range iterators: Three types with 0, 1, or 2 arguments. Examples of each type are provided, including functions that take no arguments, one argument, and two arguments.
  • What does yield() do: The yield function in a range iterator invokes the loop body. The Go compiler converts range loops with iterators into function calls. Not checking the result of yield() can cause a panic. You can call yield() multiple times or with different arguments.
  • Use cases: Main use case is to use range keyword to iterate over custom collection types. Examples include iterating over all elements, filtering values using a predicate function, and iterating while handling errors. Also shows how to handle sentinel errors and convert traditional iterators to range-compatible iterators.
  • Pull and Pull2: Go authors included Pull and Pull2 convenience functions to transform range iterator functions into traditional iterators. Demonstrated with an example of wrapping and unwrapping an iterator.
  • Readability and convention considerations: Go convention for range is different for range iterators. Single-var version may work differently. This is a new feature with no established conventions yet.
  • Conclusion: All examples are available here. Join Discord to discuss Go range iterators or Dolt.
阅读 13
0 条评论