Skip to content

Commit

Permalink
generators: add go alternative: generator func
Browse files Browse the repository at this point in the history
  • Loading branch information
shogg committed Apr 17, 2019
1 parent e53c9f3 commit 3498c6d
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 4 deletions.
32 changes: 30 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1769,10 +1769,24 @@ func Generator() chan string {
return c
}

func GeneratorFunc() func() (string, bool) {

s := []string{"hello", "world"}
i := -1

return func() (string, bool) {
i++
if i >= len(s) {
return "", false
}
return s[i], true
}
}

func main() {
gen := Generator()

for true {
gen := Generator()
for {
value, more := <-gen
fmt.Println(value, more)

Expand All @@ -1785,6 +1799,17 @@ func main() {
for value := range Generator() {
fmt.Println(value)
}

// alternatively
genfn := GeneratorFunc()
for {
value, more := genfn()
fmt.Println(value, more)

if !more {
break
}
}
}
```

Expand All @@ -1796,6 +1821,9 @@ world true
false
hello
world
hello true
world true
false
```

### datetime
Expand Down
29 changes: 27 additions & 2 deletions examples/generators.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,24 @@ func Generator() chan string {
return c
}

func GeneratorFunc() func() (string, bool) {

s := []string{"hello", "world"}
i := -1

return func() (string, bool) {
i++
if i >= len(s) {
return "", false
}
return s[i], true
}
}

func main() {
gen := Generator()

for true {
gen := Generator()
for {
value, more := <-gen
fmt.Println(value, more)

Expand All @@ -31,4 +45,15 @@ func main() {
for value := range Generator() {
fmt.Println(value)
}

// alternatively
genfn := GeneratorFunc()
for {
value, more := genfn()
fmt.Println(value, more)

if !more {
break
}
}
}

0 comments on commit 3498c6d

Please sign in to comment.