Open-Source Rust Programming • Foundational • Estimated study time: 45 minutes.
An infrastructure monitoring application rarely knows how many sensor readings it will receive in advance. Rust’s vector, Vec<T>, manages an expandable sequence while the compiler checks access and borrowing. This lesson builds on enums and pattern matching and connects to dynamic allocation in C.
Objectives and vocabulary
Distinguish length, capacity, allocation and slice; calculate element storage; append and safely inspect readings; recognize why references cannot survive an incompatible mutation; and handle capacity allocation errors. A vector owns its elements. A slice borrows a contiguous sequence without taking ownership. Length is the number of initialized elements; capacity is the number of elements that fit before growth is needed.
JetBrains Academy live-stream lesson on Rust collections, including vectors, strings and hash maps.
Memory and capacity
For nonzero-sized T, the element storage represented by capacity is B = C × S bytes, with C = capacity and S = size_of::<T>(). For a vector of u16 values with capacity 8, B = 16 bytes, excluding allocator overhead and vector metadata. If length is 5, only 10 bytes correspond to initialized elements; the remaining space cannot be read as initialized u16 values. The standard-library Vec reference does not promise a fixed growth multiplier.

Worked example: telemetry batch
The example uses Result and Option for errors and missing data, and slices to pass readings without copying the collection. The five synthetic temperatures have a sum of 140 and mean of 28.
fn average(readings: &[u16]) -> Option<f64> {
if readings.is_empty() { return None; }
let sum: u64 = readings.iter().map(|&v| u64::from(v)).sum();
Some(sum as f64 / readings.len() as f64)
}
fn main() -> Result<(), std::collections::TryReserveError> {
let mut readings: Vec<u16> = Vec::new();
readings.try_reserve(4)?;
readings.extend([24, 26, 28, 30]);
assert_eq!(readings.len(), 4);
assert!(readings.capacity() >= 4);
assert_eq!(average(&readings), Some(27.0));
assert_eq!(readings.get(4), None);
let first = readings[0]; // copy, not a retained reference
readings.try_reserve(1)?;
readings.push(32);
assert_eq!(first, 24);
assert_eq!(average(&readings), Some(28.0));
println!("len={} average={:.1}", readings.len(),
average(&readings).unwrap_or(0.0));
readings.clear();
assert_eq!(average(&readings), None);
Ok(())
}
Save as main.rs and compile with rustc –edition=2021 -D warnings main.rs, then run the executable. Expected output (not executed in this environment):
len=5 average=28.0
The program uses try_reserve before extending and before pushing to handle allocation failures at those points. get returns None for an out-of-range index instead of panicking. clear drops the initialized elements but normally preserves the allocation.
Borrowing across a possible resize
let mut v = vec![24, 26];
let first = &v[0];
v.push(28);
println!("{first}");
This example should be rejected by the borrow checker: the shared reference remains in use after a mutable operation on the vector. Growth could relocate elements. Copy the u16 value first, or finish using the reference before the mutation. This is not an assertion that every push relocates storage.
Community discussion of vector resizing and reference validity. Consult the official documentation for guarantees, rather than assuming an observed allocation pattern is contractual.
Exercises and answers
A. A Vec<u32> has length 10 and capacity 16. How many element-storage bytes are represented by its capacity? B. What does get(10) return? C. Does reserve(4) change length? D. Why pass &[u16] instead of &Vec<u16> to the mean function? E. What happens to capacity after clear? F. Why should an infrastructure service limit batch size?
Answers: A. 64 bytes. B. None. C. No. D. A slice permits any compatible contiguous borrowed data. E. The allocation is retained; length becomes zero. F. Bound memory consumption and reject untrusted input that might exhaust resources.
Safety: run examples locally against synthetic readings, never against a production control service. Do not use unsafe code to access uninitialized capacity. Further reading: The Rust Book: Storing Lists of Values with Vectors.
Editor’s Note: We volunteer daily to ensure the credibility of the information on this platform is Verifiably True. If you would like to support to help further secure the integrity of our research initiatives, please scan the QR code below

For mobile scanning, open the article on another display and scan the QR code with a Bitcoin wallet. The voluntary donation amount is 5,000 sats. Verify the receiving address 3C9o19EH5HSiwEPyCTmEKzxhNCbo2X6TTb before sending.
BitcoinVersus.Tech publishes technology and financial journalism for informational purposes and does not provide financial, investment, or legal advice.
Leave a Reply