Const Generics Fixed Size Buffers
Parametrize a ring buffer with const generics so capacity N is part of the type: RingBuffer<3> and RingBuffer<4> are distinct, incompatible types.
Code
/// 定长环形缓冲:容量 N 是类型的一部分,RingBuffer<3> 与
/// RingBuffer<4> 是不同类型,容量约束在编译期就固定
#[derive(Debug)]
struct RingBuffer<const N: usize> {
data: [Option<u32>; N],
head: usize,
len: usize,
}
impl<const N: usize> RingBuffer<N> {
fn new() -> Self {
Self { data: std::array::from_fn(|_| None), head: 0, len: 0 }
}
fn push(&mut self, value: u32) {
let slot = (self.head + self.len) % N;
if self.len == N {
// 满员:覆盖最旧元素并推进 head
self.head = (self.head + 1) % N;
self.len -= 1;
}
self.data[slot] = Some(value);
self.len += 1;
}
/// 按时间先后返回现存元素(旧 → 新)
fn chronological(&self) -> Vec<u32> {
(0..self.len)
.map(|i| self.data[(self.head + i) % N].expect("slots hold values"))
.collect()
}
}
fn main() {
let mut recent: RingBuffer<3> = RingBuffer::new();
for sample in [7, 9, 11, 13, 15] {
recent.push(sample);
}
println!("{recent:?}");
println!("latest: {:?}", recent.chronological());
}What the code does
The working surface is the functions new, push, chronological and main — everything else is wiring.
Iteration happens inside for sample in [7, 9, 11, 13, 15] — everything outside it runs once.
Applying it
The main signature reads fn new() -> Self
Output lines are prefixed (latest:), making each step’s effect easy to spot.
Start the program and main runs new, push and chronological one after another.
Statements that matter
Self { data: std::array::from_fn(|_| None), head: 0, len: 0 }
fn chronological(&self) -> Vec<u32> {
(0..self.len)
.map(|i| self.data[(self.head + i) % N].expect("slots hold values"))
.collect()
}
fn push(&mut self, value: u32) {
let slot = (self.head + self.len) % N;
if self.len == N {
// 满员:覆盖最旧元素并推进 head
self.head = (self.head + 1) % N;
self.len -= 1;
}
self.data[slot] = Some(value);
self.len += 1;
}
Interactive Tools for This Topic
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.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 Const Generics Fixed Size Buffers print when run?
- No setup needed: run the file and look for labeled lines like `latest:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.