Container Ring Circular Buffer

Rotate, link, and unlink elements in a circular ring so fixed-size buffers and round-robin schedulers reuse slots without reallocation.

GoData Integrity

Code

gosnippet
41 lines
package main

import (
	"container/ring"
	"fmt"
)

func main() {
	r := ring.New(4)
	for i := 1; i <= r.Len(); i++ {
		r.Value = i
		r = r.Next()
	}

	// Do 从当前元素起遍历整整一圈
	var values []int
	r.Do(func(v any) {
		values = append(values, v.(int))
	})
	fmt.Println("ring values:", values)

	// Move 相对当前位置前进或后退定位元素
	fmt.Println("next:", r.Move(1).Value, "prev:", r.Move(-1).Value)

	// Link 把另一个环接到当前环之后
	other := ring.New(2)
	other.Value = 10
	other.Next().Value = 20
	r.Link(other)
	fmt.Println("linked length:", r.Len())

	var after []int
	r.Do(func(v any) {
		after = append(after, v.(int))
	})
	fmt.Println("after link:", after)

	// Unlink 摘掉后续 n 个元素,返回独立的环
	rest := r.Unlink(2)
	fmt.Println("trimmed length:", r.Len(), "rest length:", rest.Len())
}

What the code does

Count the function main as the entire surface area of Container Ring Circular Buffer.

The one repetition in this snippet is the loop for i := 1; i <= r.Len(); i++.

Caveats

  • There is no dependency tree here — the platform is the whole dependency.

Applying it

Running the file prints labeled results such as ring values:, next:, linked length: — each operation’s effect is visible in the output.

Statements that carry the weight

values = append(values, v.(int))
after = append(after, v.(int))

Interactive Tools for This Topic

FAQ

What does Container Ring Circular Buffer print when run?
The script runs standalone; its 5 labeled outputs include `ring values:`, `next:`, `linked length:`.