Junior — Middle
How is information transmitted between a goroutine and an unbuffered channel of fixed capacity 1?
sobes.tech AI
Answer from AI
In Go, a channel with capacity 1 is a buffered channel that can hold exactly one element. If the channel is unbuffered (capacity 0), then the transfer blocks until it is received.
With capacity 1, the transfer works as follows:
- If the channel is empty, the sender goroutine writes the value into the buffer and continues (does not block).
- If the buffer is full (already has an element), the sender goroutine blocks until the receiver reads the value from the channel.
Thus, communication between a goroutine and a channel with capacity 1 is an exchange through a buffer that can hold one element, allowing the sender not to block if the buffer is free.
Example:
ch := make(chan int, 1) // channel with capacity 1
// Sender
go func() {
ch <- 42 // if buffer is empty, does not block
fmt.Println("Sent")
}()
// Receiver
val := <-ch
fmt.Println("Received", val)
If the sender tries to send a second element before the first is read, it will block.