Junior — Middle
What exactly happens inside a channel when data is written to it?
sobes.tech AI
Answer from AI
When writing data to a channel in Go, the following occurs:
- If the channel is buffered and there is free space in the buffer, the value is placed in the buffer, and the write operation completes immediately.
- If the channel is unbuffered or the buffer is full, the goroutine performing the write blocks and waits until another goroutine reads a value from the channel.
- When the value is transferred, it becomes available for reading by another goroutine.
Thus, the channel provides synchronization between goroutines, ensuring that data is not lost and is transmitted correctly.
Example of writing to a channel:
ch := make(chan int) // unbuffered channel
// Writing to the channel (will block until someone reads)
go func() {
ch <- 42
}()
val := <-ch // reading from the channel
fmt.Println(val) // will output 42