Sobes.tech
Junior — Middle

Can you provide an example of a scenario where a buffered channel is used for data transfer?

sobes.tech AI

Answer from AI

A buffered channel in Go is used when you need to pass data between goroutines without blocking the sender immediately if the receiver is not yet ready to accept the data. For example, in a scenario where there is a producer generating data faster than the consumer processes it, a buffered channel allows accumulating several elements without forcing the producer to wait.

Example:

package main

import (
    "fmt"
    "time"
)

func main() {
    ch := make(chan int, 3) // buffer of 3 elements

    // Producer
    go func() {
        for i := 1; i <= 5; i++ {
            fmt.Printf("Sending: %d\n", i)
            ch <- i // does not block until buffer is full
        }
        close(ch)
    }()

    // Consumer
    time.Sleep(time.Second) // simulate delay
    for val := range ch {
        fmt.Printf("Received: %d\n", val)
        time.Sleep(500 * time.Millisecond) // slow processing
    }
}

In this example, the producer can send the first 3 values into the channel buffer without blocking, and then it will wait until the consumer frees up space.

Can you provide an example of a scenario where a… - sobes.tech