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.
Code
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
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 Container Ring Circular Buffer print when run?
- The script runs standalone; its 5 labeled outputs include `ring values:`, `next:`, `linked length:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.