Sobes.tech
Junior — Middle

How is data transferred from a goroutine to a buffered channel in Go?

sobes.tech AI

Answer from AI

In Go, data transfer from a goroutine to a buffered channel is done using the send operation (chan <- value). A buffered channel has an internal buffer of fixed size, which allows the goroutine to send multiple values without immediate blocking if the buffer is not full.

Example:

ch := make(chan int, 3) // buffered channel with buffer size 3

go func() {
    ch <- 1 // send value to channel
    ch <- 2
    ch <- 3
    // if the buffer is full, the goroutine will block until space is freed
}()

// Receiving data from the channel
for i := 0; i < 3; i++ {
    val := <-ch
    fmt.Println(val)
}

If the channel buffer is not full, sending occurs immediately and the goroutine continues. If the buffer is full, the goroutine blocks until another thread reads data from the channel and frees up space in the buffer.

How is data transferred from a goroutine to a… - sobes.tech