Sobes.tech
Junior — Middle

Kuidas käitub programm, kui ta üritab kirjutada andmeid kanalile ilma buferita, kui see on algselt tühi?

sobes.tech AI

Vastus AI-lt

In Go, a channel without buffer (buffer size = 0) is synchronous. This means that when you try to write data to such a channel, and there is no ready receiver at that moment, the program blocks and waits until another goroutine reads the value from the channel.

That is, writing to a bufferless channel does not happen instantly, but requires a simultaneous receive. This ensures synchronization between sender and receiver.

Example:

ch := make(chan int) // bufferless channel

// Sending in a separate goroutine
go func() {
    ch <- 42 // blocks until someone reads
}()

// Reading
val := <-ch // after reading, the send is unblocked
fmt.Println(val)