Go 1.23 中的新内容:迭代器和 reflect.Value.Seq

  • Go 1.23 Release: The Go 1.23 release candidates are out. The author contributed four new methods: reflect.Value.Seq, reflect.Value.Seq2, reflect.Type.CanSeq, and reflect.Type.CanSeq2.
  • New Generic Custom Iteration Functions: These iterators have a tricky signature but are simple to use. An example in Go is shown, and it's compared with Python and JavaScript versions. The Go version uses the iter.Seq type, which is a generic named type for func(yield func(V) bool) where V is any type. In Go 1.24, it might be possible to write it with generic type aliases.
  • Go Channels vs. Iterators: Go channels can be used like iterators, but there were problems. Without generics, new utilities were needed for each type. Sending and receiving values through channels was slow as they were scheduled by the Go runtime scheduler. Passing around cancel channels was complex. Using a quit channel in Go was demonstrated with code adapted from a ten-year-old blog post. In Go 1.23, custom iterators are better than using close tokens.
  • reflect.Value.Seq and related methods: The doc string for reflect.Value.Seq explains its usage. Calling Seq is like a for loop over elements. CanSeq reports if a type can be used as an iterator. When iterating over a slice with Seq, only the index is yielded. To get slice elements, use Seq2. The reflect package already had a method for iterating over a map, but reflect.Value.Seq2 is nicer.
  • Proposal and Implementation: Github user [gophun] asked about calling an iterator of an unknown type. The author opened an issue to add it to the reflect package. After approval with improved method names, [qiulaidongfeng] created a changelist to implement it. There was a subsequent issue to add support for range funcs to the Go template package, which should be in Go 1.24.
阅读 19
0 条评论