github.com/searKing/golang/go@v1.2.117/go/generator/example_test.go (about) 1 // Copyright 2020 The searKing Author. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package generator_test 6 7 import ( 8 "fmt" 9 10 "github.com/searKing/golang/go/go/generator" 11 ) 12 13 func ExampleGeneratorFunc() { 14 g := func(i int) *generator.Generator { 15 return generator.GeneratorFunc(func(yield generator.Yield) { 16 if !yield(i) { 17 return 18 } 19 if !yield(i + 10) { 20 return 21 } 22 }) 23 } 24 25 gen := g(10) 26 27 for msg := range gen.C { 28 fmt.Println(msg) 29 } 30 31 // Output: 32 // 10 33 // 20 34 } 35 func ExampleGenerator_Next() { 36 g := func(i int) *generator.Generator { 37 return generator.GeneratorFunc(func(yield generator.Yield) { 38 if !yield(i) { 39 return 40 } 41 if !yield(i + 10) { 42 return 43 } 44 }) 45 } 46 47 gen := g(10) 48 49 for { 50 msg, ok := gen.Next() 51 if !ok { 52 return 53 } 54 fmt.Println(msg) 55 } 56 57 // Output: 58 // 10 59 // 20 60 } 61 62 func ExampleGeneratorWithSupplier() { 63 var g *generator.Generator 64 65 supplierC := make(chan any) 66 supplierF := func(i int) { 67 consumer := g.Yield(supplierC) 68 if !consumer(i) { 69 return 70 } 71 if !consumer(i + 10) { 72 return 73 } 74 close(supplierC) 75 } 76 g = generator.GeneratorWithSupplier(supplierC) 77 go supplierF(10) 78 79 for msg := range g.C { 80 fmt.Println(msg) 81 } 82 83 // Output: 84 // 10 85 // 20 86 } 87 88 func ExampleGeneratorVariadicFunc() { 89 g := func(i int) *generator.Generator { 90 g := generator.GeneratorVariadicFunc(func(yield generator.Yield, args ...any) { 91 i := (args[0]).(int) 92 if !yield(i) { 93 return 94 } 95 if !yield(i + 10) { 96 return 97 } 98 }) 99 100 gen := g(i) 101 return gen 102 } 103 104 gen := g(10) 105 106 for msg := range gen.C { 107 fmt.Println(msg) 108 } 109 110 // Output: 111 // 10 112 // 20 113 }