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

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/enetx/g"
     7  )
     8  
     9  func main() {
    10  	// Example 1: Map key-value pairs in a map, print the result, and close the iterator at a specific condition
    11  	m := g.NewMap[int, string]().Set(88, "aa").Set(99, "bb").Set(199, "ii").Iter()
    12  
    13  	m.
    14  		Map(func(k int, v string) (int, string) { return k + k, v }).
    15  		Range(func(k int, v string) bool {
    16  			// Close the iterator if the key is 198
    17  			if k == 198 {
    18  				return false
    19  			}
    20  
    21  			fmt.Println(k, v)
    22  			return true
    23  		})
    24  
    25  	// Example 2: Iterate over a set of integers, print each value, and stop the iteration at a specific condition
    26  	set := g.NewSet[int]().Add(1, 2, 3, 4, 5).Iter()
    27  
    28  	set.
    29  		Map(func(v int) int { return v + v }).
    30  		Range(func(v int) bool {
    31  			// Close the iterator if the value is 10
    32  			if v == 10 {
    33  				return false
    34  			}
    35  
    36  			fmt.Println(v)
    37  			return true
    38  		})
    39  }