expression
Store sensor samples in a bounded buffer
A fixed-capacity array can store a bounded number of samples without heap allocation. Keep the logical length separate from capacity; reject new items once full. This implementation initializes all slots and returns only the used prefix. Storage placement depends on the owner and compiler, not on the array type alone. Expected host stdout (not executed): full: true, samples: [12, 18] Common mistake: Using capacity as the count of valid samples or assuming fixed-capacity data always lives on the stack.
Formal Syntax & Structure
rust syntaxrust
[u16; N] + lenWorking Example
Example Snippetrust
#![no_std]pub struct Samples<const N: usize> { data: [u16; N], len: usize }impl<const N: usize> Samples<N> { pub const fn new() -> Self { Self { data: [0; N], len: 0 } } pub fn push(&mut self, value: u16) -> Result<(), u16> { if self.len == N { return Err(value); } self.data[self.len] = value; self.len += 1; Ok(()) } pub fn as_slice(&self) -> &[u16] { &self.data[..self.len] }}