Ring Buffer Over A Fixed Slice
Implement a bounded history with a fixed slice, head and tail indexes, and modulo wrap-around, overwriting the oldest entries once capacity is reached.
Code
package main
import "fmt"
// ring buffer:固定(fixed)slice + head/count,写满后覆盖最旧元素
type ringBuffer struct {
data []int
head int // 最旧元素位置
count int
}
func newRingBuffer(capacity int) *ringBuffer {
return &ringBuffer{data: make([]int, capacity)}
}
func (r *ringBuffer) push(v int) {
tail := (r.head + r.count) % len(r.data)
r.data[tail] = v
if r.count < len(r.data) {
r.count++
} else {
// 已满:head 前移一格,最旧元素被覆盖
r.head = (r.head + 1) % len(r.data)
}
}
func (r *ringBuffer) values() []int {
out := make([]int, 0, r.count)
for i := 0; i < r.count; i++ {
out = append(out, r.data[(r.head+i)%len(r.data)])
}
return out
}
func main() {
r := newRingBuffer(4)
for _, v := range []int{1, 2, 3} {
r.push(v)
}
fmt.Println("partial:", r.values())
for _, v := range []int{4, 5, 6} {
r.push(v)
}
fmt.Println("wrapped:", r.values())
}How the pieces connect
What another module actually calls is the functions newRingBuffer, push, values and main — everything else is wiring.
Iteration happens inside for i := 0; i < r.count; i++ — everything outside it runs once.
Putting it to use
The primary signature, spelled out, is func newRingBuffer(capacity int) *ringBuffer
The demo output is labeled (partial:, wrapped:), so each line traces straight back to the statement that printed it.
The entry point wires newRingBuffer, push and values together — run it once and the whole demo flows.
Core lines
return &ringBuffer{data: make([]int, capacity)}
func (r *ringBuffer) values() []int {
out := make([]int, 0, r.count)
for i := 0; i < r.count; i++ {
out = append(out, r.data[(r.head+i)%len(r.data)])
}
return out
}
func (r *ringBuffer) push(v int) {
tail := (r.head + r.count) % len(r.data)
r.data[tail] = v
if r.count < len(r.data) {
r.count++
} else {
// 已满:head 前移一格,最旧元素被覆盖
r.head = (r.head + 1) % len(r.data)
}
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Ring Buffer Over A Fixed Slice print when run?
- Run it as a complete program — the output lines carry labels such as `partial:`, `wrapped:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.