Principal
What is a channel in Go, and what is it used for?
sobes.tech AI
Answer from AI
In the Go language, a channel is a data type used for passing data between goroutines (lightweight threads). Channels provide safe communication and synchronization between parallel processes, allowing the transfer of values of a specific type.
Channels are used to organize interaction without explicit locks and shared state. They enable goroutines to exchange data and signals, which simplifies writing concurrent code.
Example of using a channel in Go:
package main
import (
"fmt"
)
func main() {
ch := make(chan int) // create a channel for transmitting int
go func() {
ch <- 42 // send value to the channel
}()
val := <-ch // receive value from the channel
fmt.Println(val) // output: 42
}
Thus, a channel is a means of communication and synchronization between goroutines in Go.