In Golang, or Go, channels are a means through which different
Think of them as pipes through which you can connect with different concurrent goroutines. The communication is bidirectional by default, meaning that you can send and receive values from the same channel.
Moreover, by default, channels send and receive until the other side is ready. This allows goroutines to synchronize without explicit locks or condition variables.
Make a channel: make(chan [value-type])
,
where [value-type] is the data type of the values to send and receive, e.g., int
.
Send and receive values: channel <-
and <- channel
,
where <-
is the channel operator.
Close a channel: close(channel)
.
After closing, no value will be sent to the channel.
Both sending and receiving are blocking operations by default.
greet
as a goroutine.greet
is blocked when it encounters <- c
and waits to receive a value.greet
function.package mainimport "fmt"// Prints a greeting message using values received in// the channelfunc greet(c chan string) {name := <- c // receiving value from channelfmt.Println("Hello", name)}func main() {// Making a channel of value type stringc := make(chan string)// Starting a concurrent goroutinego greet(c)// Sending values to the channel cc <- "World"// Closing channelclose(c)}