Last active
August 29, 2015 14:01
-
-
Save jakecoffman/8dc2e69064a83a332826 to your computer and use it in GitHub Desktop.
Python style generator in Golang example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
func main() { | |
gen := GetIncrementor() | |
for i := gen(); i <= 10; i = gen() { | |
fmt.Println(i) | |
} | |
} | |
func GetIncrementor() func() int { | |
c := make(chan int) | |
go func() { | |
i := 0 | |
for { | |
i += 1 | |
c <- i | |
} | |
}() | |
return func() int { | |
return <-c | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def get_incrementor(): | |
i = 0 | |
while True: | |
i += 1 | |
yield i | |
if __name__ == "__main__": | |
gen = get_incrementor() | |
for i, v in enumerate(gen): | |
if i >= 10: | |
break | |
print v |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment