Welcome to our comprehensive guide on using the range keyword to iterate over channels in Golang! In this lesson, we'll explore:
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.
// Declaring a channel of type int
myChannel := make(chan int)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.
To iterate over a channel using the range keyword, we can use the following structure:
// 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.
myChannel <- 42close(myChannel)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)
}
}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
}
}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! 💡🎯📝