Share & grow the world's code base!

Delve into a community where programmers unite to discover code snippets, exchange skills, and enhance their programming proficiency. With abundant resources and a supportive community, you'll find everything essential for your growth and success.

1 snippets
  • Iterators in Go

    package main
    
    import (
    	"fmt"
    	"iter"
    )
    
    // As long as the loop continues to run, yield will keep returning true,
    // indicating that more values exist.
    // However, if the loop terminates (for instance, due to a break or return),
    // yield will return false.
    // This allows to perform any necessary cleanup.
    func generateFibonacci() iter.Seq[int] {
    	return func(yield func(int) bool) {
    		a, b := 1, 1
    
    		for {
    			if !yield(a) {
    				fmt.Println("Stop sequence")
    				return
    			}
    
    			a, b = b, a+b
    		}
    	}
    }
    
    func main() {
    	for v := range generateFibonacci() {
    		fmt.Println(v)
    
    		if v > 10 {
    			break
    		}
    	}
    }
    
    // $ go run main.go 
    // 1
    // 1
    // 2
    // 3
    // 5
    // 8
    // 13
    // Stop sequence

    A Golang iterator is a function that “yields” one result at a time, rather than computing an entire set of results and returning them all at once. When you use an iterator in a for loop with a range expression, the loop executes once for each value returned by the iterator. Here is an example of range over iterator in Go.