Channels in Go allow you to pass values between concurrent goroutines. Channels can be thought of as pipes that connect concurrent goroutines and allow them to communicate.
Here’s an example:
package main
import "fmt"
func main() {
messages := make(chan string)
go func() { messages <- "ping" }()
msg := <-messages
fmt.Println(msg)
}
In the example above, we create a channel of strings using make(chan string)
. Then, we create an anonymous function that sends the string “ping” to the channel. Finally, in the main
function, we receive the message from the channel and print it out. The output will be ping
.
Channels can also be used to synchronize concurrent goroutines. Here’s an example:
package main
import "fmt"
func worker(done chan bool) {
fmt.Print("working...")
done <- true
}
func main() {
done := make(chan bool, 1)
go worker(done)
<-done
fmt.Println("done")
}
In the example above, we create a channel done
of type bool
using make(chan bool, 1)
. Then, we create a worker function that accepts a channel of type bool
and sends the value true
to the channel when it is done working. Finally, in the main
function, we receive from the done
channel to wait for the worker to finish. The output will be working...done
.
Here’s an additional example of using channels:
package main
import "fmt"
func sum(a []int, c chan int) {
total := 0
for _, v := range a {
total += v
}
c <- total
}
func main() {
a := []int{7, 2, 8, -9, 4, 0}
c := make(chan int)
go sum(a[:len(a)/2], c)
go sum(a[len(a)/2:], c)
x, y := <-c, <-c
fmt.Println("sum of a[:len(a)/2] and a[len(a)/2:] =", x+y)
}
In this example, we have a sum
function that takes an integer array a
and a channel c
. The function calculates the sum of the integers in a
and sends the result to channel c
.
In the main
function, we create a channel c
and launch two goroutines to calculate the sum of two parts of the integer array a
. The two sums are then received from channel c
and added together, before being printed out.
Leave a Reply