Channels in Go
Golang Concepts
Go: Channels
Channels are a core feature of concurrency in Go.
Channels provide a way for goroutines to communicate and synchronize with each other by sending and receiving values. Channels are typed, which means that they can only be used to send and receive values of a specific type.
How to createchannels in Go?
In Go, channels are created using the make
function, which takes the type of values that the channel will send and receive as an argument.
Below is an example of how to create a channel of integers:
ch := make(chan int)
Send a value on a channel
To send a value on a channel, we use the <-
operator followed by the value to send
ch <- 42
Receive a value from a channe
To receive a value from a channel, we use the <-
operator on the left side of an
x := <-ch
How to use channels in conjunctions golang
Channels can also be used in conjunction with the "select" statement to wait for multiple channels to become available for sending or receiving. Here's an example:
func main() {
ch1 := make(chan int)
ch2 := make(chan string)
go func() {
ch1 <- 42
}()
go func() {
ch2 <- "hello"
}()
select {
case x := <-ch1:
fmt.Println("received", x)
case s := <-ch2:
fmt.Println("received", s)
}
}
In this example, we create two channels, ch1
and ch2
, and create two goroutines that send values on each channel. We then use the select
statement to wait for either channel to become available for receiving. When a value is received on one of the channels, we print it to the console.
Overall, channels are a powerful tool for synchronizing and communicating between goroutines in Go. By using channels and goroutines together, we can write efficient and safe concurrent programs.