Middle
Mis on kanal Go-s? Millised on kanalite tüübid? Kuidas erinevad buferiga ja buferita kanalid?
sobes.tech AI
Vastus AI-lt
A channel in Go is a data type used for transmitting values between goroutines, ensuring synchronization and data exchange.
Types of channels:
- Unbuffered channels — do not have an internal buffer, sending blocks until the receiver reads the value.
- Buffered channels — have an internal buffer of fixed size, and sending blocks only if the buffer is full.
Differences:
- In unbuffered channels, sender and receiver must be ready at the same time, providing strict synchronization.
- In buffered channels, the sender can place multiple values into the buffer without waiting for the receiver, until the buffer is full.
Example of creating and using a buffered channel:
ch := make(chan int, 2) // buffer for 2 elements
ch <- 1
ch <- 2
// ch <- 3 // blocks until space is available
fmt.Println(<-ch) // 1
fmt.Println(<-ch) // 2