Go Range over Channels 🎯

beginner
24 min

Go Range over Channels 🎯

Welcome to our comprehensive guide on using the range keyword to iterate over channels in Golang! In this lesson, we'll explore:

  • What are Channels?
  • Understanding the Range Keyword
  • Iterating over Channels with Range
  • Advanced Channel Operations
  • Practical Examples

What are Channels? 📝

In Go, channels are the pipelines used for communication between goroutines. Channels can send and receive values of any type. They're a powerful tool for handling concurrency and synchronization in your Go programs.

go
// Declaring a channel of type int myChannel := make(chan int)

Understanding the Range Keyword 💡

The range keyword in Go is used to iterate over collections such as arrays, slices, maps, and channels. It's a versatile tool for looping through data structures and performing operations on each element.

Iterating over Channels with Range 🎯

To iterate over a channel using the range keyword, we can use the following structure:

go
// Receiving values from the channel for value := range myChannel { // Perform operations on the received value }

In this loop, the value variable holds the received value from the channel on each iteration.

Advanced Channel Operations 💡

  • Sending values to a channel:
go
myChannel <- 42
  • Closing a channel to indicate no more values will be sent:
go
close(myChannel)

Practical Examples 📝

Example 1: Sending and Receiving Values

go
package main import ( "fmt" "time" ) func main() { myChannel := make(chan int) go func() { for i := 0; i < 5; i++ { myChannel <- i time.Sleep(100 * time.Millisecond) } close(myChannel) }() for value := range myChannel { fmt.Println("Received:", value) } }

Example 2: Sending Messages between Goroutines

go
package main import ( "fmt" "time" ) func worker(id int, jobs <-chan int, results chan<- int) { for j := range jobs { fmt.Println("Worker", id, "received job", j) time.Sleep(time.Second) fmt.Println("Worker", id, "finished job", j) results <- j * 2 } } func main() { jobs := make(chan int, 100) results := make(chan int, 100) var workers = 5 for w := 1; w <= workers; w++ { go worker(w, jobs, results) } for j := 1; j <= 9; j++ { jobs <- j } close(jobs) for a := 1; a <= workers; a++ { <-results } }

Quiz 📝

Quick Quiz
Question 1 of 1

What does the `close()` function do when called on a channel?

By mastering the Go range keyword and channels, you'll be well-equipped to handle concurrent operations in your Go programs. Happy coding! 💡🎯📝