github.com/enetx/g@v1.0.80/examples/iter/iter_from_chan.go (about)

     1  package main
     2  
     3  import (
     4  	"github.com/enetx/g"
     5  	"github.com/enetx/g/f"
     6  )
     7  
     8  func main() {
     9  	ch := make(chan int)
    10  	go func() {
    11  		defer close(ch)
    12  		for i := 1; i <= 5; i++ {
    13  			ch <- i
    14  		}
    15  	}()
    16  
    17  	// Convert the channel into an iterator and apply filtering and mapping operations.
    18  	g.FromChan(ch).
    19  		Filter(f.Even).                        // Filter even numbers
    20  		Map(func(i int) int { return i * 2 }). // Double each element
    21  		Collect().                             // Collect the results into a slice
    22  		Print()                                // Print the collected results: Slice[4, 8]
    23  }