Junior — Middle
What operations are available for data transfer channels?
sobes.tech AI
Answer from AI
In Go, channels are used for data transfer between goroutines and provide synchronization. Main operations with channels:
- Sending data:
ch <- value— sends a value into the channel. - Receiving data:
value := <-ch— receives a value from the channel. - Closing the channel:
close(ch)— closes the channel, after which no more data can be sent, but remaining data can be read. - Checking if the channel is closed during read:
value, ok := <-ch— ifokisfalse, the channel is closed and no more data is available.
Example:
ch := make(chan int)
go func() {
ch <- 42
close(ch)
}()
value, ok := <-ch
if ok {
fmt.Println("Received:", value)
} else {
fmt.Println("Channel is closed")
}