How do I implement a ring buffer in Go?

A ring buffer, also known as a circular buffer, is a fixed-size data structure that efficiently uses memory by overwriting old data when new data arrives. This makes it particularly useful for applications such as streaming data, producer-consumer problems, and buffering I/O.

Implementing a Ring Buffer in Go

Below is an example implementation of a ring buffer in Go.

package main import ( "fmt" ) type RingBuffer struct { buffer []interface{} head int tail int size int } func NewRingBuffer(capacity int) *RingBuffer { return &RingBuffer{ buffer: make([]interface{}, capacity), head: 0, tail: 0, size: 0, } } func (rb *RingBuffer) Push(value interface{}) { rb.buffer[rb.tail] = value rb.tail = (rb.tail + 1) % len(rb.buffer) if rb.size == len(rb.buffer) { rb.head = (rb.head + 1) % len(rb.buffer) // Overwrite if full } else { rb.size++ } } func (rb *RingBuffer) Pop() (interface{}, bool) { if rb.size == 0 { return nil, false } value := rb.buffer[rb.head] rb.head = (rb.head + 1) % len(rb.buffer) rb.size-- return value, true } func (rb *RingBuffer) IsEmpty() bool { return rb.size == 0 } func main() { rb := NewRingBuffer(5) rb.Push(1) rb.Push(2) rb.Push(3) rb.Push(4) rb.Push(5) rb.Push(6) // This will overwrite the oldest value (1) for !rb.IsEmpty() { if value, ok := rb.Pop(); ok { fmt.Println(value) } } }

ring buffer circular buffer Go data structure memory management