Sobes.tech
Junior — Middle

What happens in the system if the channel length is not specified during its creation?

sobes.tech AI

Answer from AI

If the length of the channel is not specified when creating it in Go, an unbuffered channel is created. Such a channel has the following features:

  • Sending (chan <-) blocks until another goroutine reads a value from the channel.
  • Receiving (<- chan) blocks until a value is sent to the channel.

This means that send and receive operations are synchronized directly between goroutines, ensuring strict synchronization.

Example of creating an unbuffered channel:

ch := make(chan int) // length not specified, channel is unbuffered

If asynchronous sending without blocking is needed, you should specify the buffer length, for example:

ch := make(chan int, 10) // buffer for 10 elements

In conclusion, not specifying the length when creating a channel means that the channel will operate in synchronous mode.