Junior — Middle
What role do channels play in the Go programming language and what are they used for?
sobes.tech AI
Answer from AI
Channels in Go are used for safe data exchange between goroutines. They provide synchronization and message passing, allowing goroutines to communicate without shared variables and locks.
Main features of channels:
- They allow transmitting values of a specific type.
- They support blocking send and receive, simplifying synchronization.
- They can be buffered or unbuffered.
Example of channel usage:
ch := make(chan int)
// Sending in a goroutine
go func() {
ch <- 42
}()
// Receiving from the channel
value := <-ch
fmt.Println(value) // Will print 42
Thus, channels help build concurrent programs using the CSP (Communicating Sequential Processes) model.