Go by Example: Channel Buffering

Here’s an example that demonstrates channel buffering:

package main

import "fmt"

func main() {
    c := make(chan int, 2)
    c <- 1
    c <- 2
    fmt.Println(<-c)
    fmt.Println(<-c)
}

In this example, we create a channel c with a buffer size of 2. This means that c can store up to 2 values before blocking. We then send the values 1 and 2 to the channel, which are stored in the buffer.

Finally, we receive the two values from the channel and print them out. As the channel is buffered, the <-c statements do not block and the values are retrieved in the order they were sent.

Here’s another example to demonstrate channel buffering:

package main

import "fmt"

func main() {
    c := make(chan int, 3)
    go func() {
        for i := 1; i <= 3; i++ {
            c <- i
        }
        close(c)
    }()

    for v := range c {
        fmt.Println(v)
    }
}

In this example, we create a channel c with a buffer size of 3. We then create a goroutine that sends the values 1, 2 and 3 to the channel and then closes it.

Finally, we use a for range loop to receive the values from the channel and print them out. Since the channel is buffered, the values are retrieved from the buffer and not blocked.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *