Generators in Go

• 1 min read

While Go does not have an official construct for generators, it is possible to use channels to achieve the same effect. Below is a function called count that generates numbers from 0 to n.

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Generator that counts to n //
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~//

func count(n int) (chan int) {
	ch := make(chan int)
	
	go func () {
		for i := 0; i < n; i++ {
			ch <- i
		}
		close(ch)
	}()
	
	return ch
}

func main() {
	for i := range count(10) {
		fmt.Println("Counted", i)
	}
}

As you can see, our main function can now use count like a generator without needing to handle channel creation.

If you enjoyed this tutorial, please consider sponsoring my work on GitHub 🤗

Now look what you've done 🌋
Stop clicking and run for your life! 😱
Uh oh, I don't think the system can't handle it! 🔥
Stop it, you're too kind 😄
Thanks for the love! ❤️
Thanks, glad you enjoyed it! Care to share?
Hacker News Reddit

×

Recommended Posts ✍🏻

See All »
• 3 min read
✨ HTML Share Buttons
Read Post »
• 3 min read
🚅 Next Stop, Yaak
Read Post »
• 4 min read
💻 Wait for User to Stop Typing, in JavaScript
Read Post »