How to Implement a Ring Buffer in Go

Implement a Go ring buffer using a slice with head/tail indices and modulo arithmetic for wrapping.

Go has no built-in ring buffer; implement one using a slice with head and tail indices that wrap around using modulo arithmetic.

package main

import "fmt"

type RingBuffer struct {
    buf  []int
    head int
    tail int
    size int
}

func NewRingBuffer(capacity int) *RingBuffer {
    return &RingBuffer{buf: make([]int, capacity), size: capacity}
}

func (r *RingBuffer) Push(v int) bool {
    if r.head == (r.tail+1)%r.size {
        return false // Full
    }
    r.buf[r.tail] = v
    r.tail = (r.tail + 1) % r.size
    return true
}

func (r *RingBuffer) Pop() (int, bool) {
    if r.head == r.tail {
        return 0, false // Empty
    }
    v := r.buf[r.head]
    r.head = (r.head + 1) % r.size
    return v, true
}

func main() {
    rb := NewRingBuffer(3)
    rb.Push(1); rb.Push(2)
    if v, ok := rb.Pop(); ok {
        fmt.Println(v) // 1
    }
}