無根生

無根生

Learned a new way to write code from the official repository (1)

This series will be relatively short, consider it as a note.

A new usage method learned from the official library, recently planning to rewrite the project, intending to find inspiration from other libraries to see how they handle SSE data streams. I looked at the gemini golang library, which uses iter, Seq2 to generate iterator functions.

The function signature is as follows:

type Seq2[K, V any] func(yield func(K, V) bool)

Here is a simple example:

package main

import (
	"fmt"
	"iter"
)

func iterateArray(a []string) iter.Seq2[string, error] { 
	return func(yield func(string, error) bool) {
		for _, s := range a {
			if s == "exit" {
				yield("", fmt.Errorf("exit")) // return error and interrupt
				return 
			}
			if !yield(s, nil) { // if yield returns false, stop iterating
				return
			}
		}
	}
}

func main() {
	ia := iterateArray([]string{"a", "b", "c", "exit", "d"})
	for k, v := range ia {
		fmt.Println(k, v)
	}
}

When you use for range to iterate over the sequence returned by iterateArray, the for range loop mechanism provides this yield function.

Yield returning false indicates that the for range has been interrupted, stopping the iteration.

When receiving "exit," the iterator actively stops.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.