github.com/goplus/llgo@v0.8.3/_demo/genints/gen_ints.go (about)

     1  package main
     2  
     3  import (
     4  	"github.com/goplus/llgo/c"
     5  )
     6  
     7  type generator struct {
     8  	val c.Int
     9  }
    10  
    11  func (g *generator) next() c.Int {
    12  	g.val++
    13  	return g.val
    14  }
    15  
    16  func genInts(n int, gen func() c.Int) []c.Int {
    17  	a := make([]c.Int, n)
    18  	for i := range a {
    19  		a[i] = gen()
    20  	}
    21  	return a
    22  }
    23  
    24  func main() {
    25  	// generate 5 random integers
    26  	for _, v := range genInts(5, c.Rand) {
    27  		c.Printf(c.Str("%d\n"), v)
    28  	}
    29  
    30  	// generate 5 integers, each is double of the previous one
    31  	initVal := c.Int(1)
    32  	ints := genInts(5, func() c.Int {
    33  		initVal *= 2
    34  		return initVal
    35  	})
    36  	for _, v := range ints {
    37  		c.Printf(c.Str("%d\n"), v)
    38  	}
    39  
    40  	// generate 5 integers, each is incremented by 1
    41  	g := &generator{val: 1}
    42  	for _, v := range genInts(5, g.next) {
    43  		c.Printf(c.Str("%d\n"), v)
    44  	}
    45  }
    46  
    47  /* Posible output:
    48  16807
    49  282475249
    50  1622650073
    51  984943658
    52  1144108930
    53  2
    54  4
    55  8
    56  16
    57  32
    58  2
    59  3
    60  4
    61  5
    62  6
    63  */